import {
  api,
  util,
  storage
} from "../util";
import {
  router
} from '../router';
// 导入核心模块业务
import {
  config
} from "./gloab";
import authorize from './authorize.js'
import {
  mall,detail
} from './mall.js'
import {
  orderPay
} from './pay.js'
import {
  GoodsNumCache
} from './propertycache.js'
import { alert, deepClone, getTabbar, isEmpty, type } from "../newUtil";
import { setStorageSync } from "../compatible";
import { calculation } from "../common/math";

const app = getApp();
/*快速下单 */
const fastorder = {
  /*加载常购商品 */
  loadList(index, data, callback) {
    if (index == 1) {
      mall.load_favorite_list(data, callback);
      return;
    } else if (index == 2) {
      mall.load_offen_buy_list(data, callback);
      return;
    } else if (index == 3) {
      orderlist.loadList(7, data, callback);
    }
  },
  /*再次购买 */
  aginBuy: function(id,callback) {
    var entity = authorize.getEntity();
    var param = {
      orderId: id,
      token: entity && entity.manager ? entity.manager.Token : '',
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.trade.keepbuy", param, function(res) {
      res=res.data;
      if (res.Success) {
        setStorageSync('tabindex', app.dns.cartNum);
        router.switchTab({
          path: "cart"
        });
        //更新购物车数量
      } else {
        util.tips(res.Message);
      }
      if (callback && typeof(callback)=="function"){
        callback();
      }
    },"3.0",null,false);
  },
  /*拍照下单记录 */
  loadPhotoRecords:function(data,callback){
    var entity = authorize.getEntity();
    let param = {
      PageIndex:data.PageIndex,
      PageSize:data.PageSize,
      Token:entity && entity.manager ? entity.manager.Token : '',
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.takephotos.page", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }else{
        util.tips(res.Message);
      }
    }, "3.0", null, false);
  }
}
/**订单 */
const order = {

  /**立即下单,返回base64的加密字符串 */
  buyNow(goodslist, goodsMode) {
    var ary = [];
    for (var i = 0; i < goodslist.length; i++) {
      var buyGood = goodslist[i];
      if (buyGood.ProductId == goodsMode.ProductId) {
        if (buyGood.CartCount > 0) {
          //单位换算比例 
          var translated = buyGood.Translated || buyGood.Radix;
          translated = (isNaN(translated) || translated == undefined) ? 1 : translated;
          var num = buyGood.CartCount; //当前个数
          ary.push("<Goods><SupplierId>" + goodsMode.SupplierId + "</SupplierId>");
          ary.push("<FlagId>2</FlagId><BuyTypeId>0</BuyTypeId>");
          ary.push("<BuyType>Product</BuyType>");
          ary.push("<productid>" + buyGood.ProductId + "</productid>");
          ary.push("<goodsid>" + buyGood.GoodsId + "</goodsid>");
          ary.push("<specvalue><![CDATA[" + (buyGood.SpecValue == "无" ? "" : buyGood.SpecValue) + "]]></specvalue>");
          ary.push("<quantity>" + num * translated + "</quantity>");
          ary.push("<DiscountType>" + (buyGood.DiscountType || 0) + "</DiscountType>");
          ary.push("<DiscountId>" + buyGood.DiscountId + "</DiscountId>");
          ary.push("<AuxUnit>" + (buyGood.DefaultUnit || buyGood.Unit) + "</AuxUnit>");
          ary.push("<AuxRate>" + translated + "</AuxRate>");
          ary.push("<AuxQty>" + num + "</AuxQty>");
          ary.push("</Goods>");
        }
      }
    }
    if (ary.length <= 0) {
      return "";
    }
    var productinfo = ary.join('');
    return util.base64_encode(productinfo);
  },
  /**
   * @param {Number} quantityDigits 保留的小数位数
   */
  buyNows(goodslist, goodsMode, quantityDigits){
    var ary = [];
    for(var i=0;i<goodslist.length;i++){
      var buyGood = goodslist[i];
      if (buyGood.ProductId == goodsMode.ProductId) {
        var unit = goodslist[i].AuxiliaryUnits;
        for(var j=0;j<unit.length;j++){
          if(unit[j].Qty > 0){
            var translated = unit[j].Translated,
            units = unit[j].Name;
            const quantity = util.keepDecimal("ceil", translated * (unit[j].Qty || 0), quantityDigits)
            ary.push("<Goods><SupplierId>" + goodslist[i].SupplierId + "</SupplierId>");
            ary.push("<FlagId>2</FlagId><BuyTypeId>0</BuyTypeId>");
            ary.push("<BuyType>Product</BuyType>");
            ary.push("<productid>" + goodslist[i].ProductId + "</productid>");
            ary.push("<goodsid>" + goodslist[i].GoodsId + "</goodsid>");
            ary.push("<specvalue><![CDATA[" + (goodslist[i].SpecValue == "无" ? "" : goodslist[i].SpecValue) + "]]></specvalue>");
            ary.push("<quantity>" +(quantity || 0) + "</quantity>");
            ary.push("<DiscountType>" + (goodslist[i].DiscountType || 0) + "</DiscountType>");
            ary.push("<DiscountId>" + (goodslist[i].DiscountId || 0) + "</DiscountId>");
            ary.push("<AuxUnit>" + (units) + "</AuxUnit>");
            ary.push("<AuxRate>" + translated + "</AuxRate>");
            ary.push("<AuxQty>" + (unit[j].Qty || 0) + "</AuxQty>");
            ary.push("</Goods>");
          }
        }
      }
    }
    if (ary.length <= 0) {
      return "";
    }
    var productinfo = ary.join('');
    console.log(productinfo,'------==productinfo')
    return util.base64_encode(productinfo);
  },

  /**初始化订单确认页面的数据*/
  initOrderConfirmData(pdata, callback) {
    var productInfo = util.base64_decode(pdata).replace(/\0/g, "");
    var entity = authorize.getEntity();
    var param = {
      Token:entity && entity.manager ? entity.manager.Token : '',
      FKFlag: app.dns.proprietor,
      SupplierId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      StoreId: entity ? entity.fkId : 0,
      productinfo: productInfo
    };

    util.post("order.trade.calc", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(true, res.Content);
        }
      } else {
        if (callback != undefined && typeof(callback) == "function") {
          callback(false, res.Message);
        }
      }
    }, "3.0");
  },
 
  packOrderInfo(data) {
    let VirtualImage = data.VirtualImage || []
    let attachment = ``
    VirtualImage.map((item) => {
      attachment += `
        <attachment>
          <name><![CDATA[${item.name || '附件文件'}]]></name>
          <url>${item.src}</url>
        </attachment>
      `
    })
    //数据拼装
    var xmlAary = "<root><Buy>";

    xmlAary += `
    <Taxes>${data.Taxes}</Taxes>
    <Quantity>${data.Quantity}</Quantity>
    <ProductIds><![CDATA[${data.ProductIds}]]></ProductIds>
    <ProductInfo><![CDATA[${data.ProductInfo}]]></ProductInfo>
    <AreaId>${data.areaCode || ''}</AreaId>
    <IsDelivery>${data.IsDelivery}</IsDelivery>
    <PickPointId>${data.PickPointId}</PickPointId>
    <LogisticsMode>${data.LogisticsMode}</LogisticsMode>
    `
    xmlAary += `
    <AddressId>${data.consignee.AddressId || 0}</AddressId>
    <AddressIds>${data.consignee.AddressId || 0}</AddressIds>
    <AddressProvince><![CDATA[${data.AddressProvince}]]></AddressProvince>
    <PayTypeId>${data.PayTypeId}</PayTypeId>
    <PaymentId>0</PaymentId>
    <CouponDiscount>${data.CouponDiscount}</CouponDiscount>
    <CouponIds>${data.CouponIds}</CouponIds>
    <PayDiscount>0</PayDiscount>
    <DiscountAmount>${data.DiscountAmount}</DiscountAmount>
    <Payables>${data.Payables}</Payables>
    <DeductionTotal>${data.DeductionTotal}</DeductionTotal>
    <InvoiceType>${data.InvoiceType}</InvoiceType>
    <AccountDeductionIntegral>${data.UseIntegral}</AccountDeductionIntegral>
    <FreightDeductionIntegral>${data.FreightDeductionIntegral || 0}</FreightDeductionIntegral>
    <BuyRemark><![CDATA[${data.BuyRemark}]]></BuyRemark>
    <BuyFile>${attachment}</BuyFile>
    </Buy>
    `
    xmlAary += "<Suppliers>";
    var odrAry = data.spOder;
    for (let j = 0; j < odrAry.length; j++) {
      xmlAary += "<Supplier>";
      xmlAary += "<SupplierId>" + odrAry[j].SupplierId + "</SupplierId>";
      xmlAary += "<BuyRemark></BuyRemark>";
      xmlAary += "<Coupon>";
      xmlAary += "<CouponId>" + data.CouponIds + "</CouponId>";
      xmlAary += "<CouponNumber></CouponNumber>";
      xmlAary += "<CouponPassword></CouponPassword>";
      xmlAary += "</Coupon>";
      xmlAary += "</Supplier>";
    }
    xmlAary += "</Suppliers>";
    //单品备注
    let products = odrAry.map(item => {return item.Products;})[0];
    let goodsRemark = ''
    for(let i = 0 ; i < products.length; i++){
      for(let j = 0 ; j < products[i].Goods.length; j++){
        let goods = products[i].Goods[j];
        // 存在商品备注，才加入xml主体内
        if (!isEmpty(goods.BuyRemark)) {
          goodsRemark += "<GoodsRemark>";
          goodsRemark += "<GoodsId>" + goods.GoodsId + "</GoodsId>";
          goodsRemark += "<BuyRemark><![CDATA[" + goods.BuyRemark + "]]></BuyRemark>";
          goodsRemark += "<AuxRate>" + (goods.AuxRate || 1) + "</AuxRate>";
          goodsRemark += "</GoodsRemark>";
        }
      }
    }
    // 至少有一个remark才增加goodsRemarks标签
    if (!isEmpty(goodsRemark)) {
      xmlAary += "<GoodsRemarks>" + goodsRemark + "</GoodsRemarks>"
    }
    //快递&送货时间
    if (data.DeliveryId > 0 || !isEmpty(data.DeliveryTime)) {
      xmlAary += "<Delivery>";
      xmlAary += "<DeliveryId>"+data.DeliveryId+"</DeliveryId>";
      xmlAary += "<DeliveryTime>"+data.DeliveryTime+"</DeliveryTime>";
      xmlAary += "</Delivery>";
    }
    // 当自提并且没有开启自提需要收货地址时，不传地址信息
    // 其他都需要传
    if (!data.needNotConsignee) {
      //收货信息
      xmlAary += "<Consignee>";
      xmlAary += "<Province><![CDATA[" + (data.consignee.Province) + "]]></Province>";
      xmlAary += "<City><![CDATA[" + (data.consignee.City) + "]]></City>";
      xmlAary += "<Area><![CDATA[" + (data.consignee.Area) + "]]></Area>";
      xmlAary += "<Address><![CDATA[" + (data.consignee.Address) + "]]></Address>";
      xmlAary += "<Name><![CDATA[" + (data.consignee.Name) + "]]></Name>";
      xmlAary += "<Mobile>" + (data.consignee.Mobile) + "</Mobile>";
      xmlAary += "</Consignee>";
    }
    //发票信息
    xmlAary += data.invoice;
    xmlAary += data.orderData;
    xmlAary += "</root>";
    return xmlAary.toString();
  },
  /**提交订单 */
  submitOrder(xmlAary, callback) {
    var entity = authorize.getEntity();
    var param = {
      Async:1,
      order: xmlAary.toString(),
      Token: entity && entity.manager ? entity.manager.Token : '',
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
    };
    util.post("order.trade.submits", param, function(res) {
      res = res.data;
      if (callback != undefined && typeof (callback) == "function") {
        callback(res);
      }
    }, "3.0", null, false);
  },
   //获取订单自定义字段信息
   orderCustomization:function(callback){
    var entity = authorize.getEntity();
    var param = {
      token:entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };
    util.post("order.customizefields.get", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.alert("操作失败:" + res.Message);
      }
    }, "3.1");
  },
  //获取订单自定义字段信息
  customizefields:function(callback){
    var entity = authorize.getEntity();
    var param = {
      token:entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };
    util.post("order.customizefields.filter", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.alert("操作失败:" + res.Message);
      }
    }, "3.1");
  },
  /**异步回调 */
  orderCallBack(id,callback) {
    var entity = authorize.getEntity();
    var param = {
      Token: entity && entity.manager ? entity.manager.Token : '',
      FoundOrderId:id,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
    };

    util.post("order.trade.selectorder", param, function (res) {
      res = res.data;
      if (callback != undefined && typeof (callback) == "function") {
        callback(res);
      }
    }, "3.0", null, false);
  },
  /**
   * 提交拍照订单
   */
  photoOrderSubmit(list,callback){
    var entity = authorize.getEntity();
    let param = {
      Id:0,
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity ? entity.fkId : 0,
      Photos: list,
      Remark: '',
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.takephotos.save", param, function(res) {
      res = res.data;
      if (callback != undefined && typeof (callback) == "function") {
        callback(res);
      }
    }, "3.0", null, false);
  },
    /**
   * 同步微信发货组件发货信息
   */
  getWxShippingInfo: function(orderId, callback) {
    var entity = authorize.getEntity() || {};
    var param = {
      orderId: orderId,
      token:entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId,
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0,
    };
    util.post("order.uploadwxshippinginfo", param,
      function(res) {
        res = res.data
        if (callback != undefined && typeof (callback) == "function") {
          callback(res)
        }
      }, "3.0", null, false);
  },
}

/*购物车 */
const cart = {
  /*加载购物车列表 */
  loadList: function(data,callback) {
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKFlag: 2,
      AreaId: data.areaCode,
      Token: entity.manager.Token
    };
    util.post("order.cart.newlist", param, function(res) {
      var res = res.data;
      if (res.Success) {
        var source = res.Content.Sellers || [];
        var goods_list = [];
        if (source.length > 0) {
          source.map(function(seller, i) {
            seller.PromotRules.map(function(rule, j) {

              let ruleType = rule.RuleType
              let productId = rule.RuleId // 将ruleid作为唯一标识
              let goodsIdStr = ''
              let auxRateStr = ''

              rule.Products.map(function(p, k) {
                p.Goods.map(function(g, l) {
                  g.SBuyLowerLimit = g.BuyLowerLimit || 0;
                  g.SBuyUpperLimit = g.BuyUpperLimit || 0;
                  g.SStock = g.Stock || 0;
                  if (g.DiscountType != 5 && p.Goods.length>1) {
                      var otherUnitQuantity = 0;
                      for (let n = 0; n < p.Goods.length; n++) {
                          var item = p.Goods[n];
                          if (item.GoodsId==g.GoodsId&&item.DiscountType!=5&&item.AuxRate!=g.AuxRate&&item.AuxQty>0) {
                              otherUnitQuantity += (item.AuxQty || 0) * (item.AuxRate || 1);
                          }
                      }
                      g.BuyLowerLimit = g.SBuyLowerLimit > 0 && g.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", g.SBuyLowerLimit - otherUnitQuantity, data.quantityDigits) : 0;
                      g.BuyUpperLimit = g.SBuyUpperLimit > 0 && g.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", g.SBuyUpperLimit - otherUnitQuantity, data.quantityDigits) : 0;
                      g.Stock = g.SStock > 0 && g.SStock > otherUnitQuantity ? util.keepDecimal("ceil", g.SStock - otherUnitQuantity, data.quantityDigits) : 0;
                  }
                  if (g.DiscountType > 0 && g.DiscountId > 0) {
                    g.linkParam = `id=${p.ProductId}&ptype=${rule.RuleType==5?0:3}&discounttype=${g.DiscountType}&discountid=${g.DiscountId}`;
                  } else {
                    g.linkParam = `id=${p.ProductId}`;
                  }
                  //下架商品取消选中状态
                  if (g.Shelved == 0 || !p.PurchasePower || ((g.Stock <= 0 || g.Stock < g.BuyLowerLimit) && p.ZeroStockBuy == 0)) {
                    g.IsChecked = 0;
                  }
                  //促销信息展示块
                  g.info = [];
                  g.gift = [];
                  //阶梯价格
                  cart.displayLadderPrice(g, seller.DeductRate || 0, app.dns.fkWay,data.Currency);
                  //设置价格
                  cart.displayPrice(g);
                  
                  if(ruleType != 5) {
                    goods_list.push({
                      productId: p.ProductId,
                      goodsId: g.GoodsId,
                      num: g.AuxQty,
                      radix: g.AuxRate
                    });
                  } else {
                    goodsIdStr += g.GoodsId + '_'
                    auxRateStr += g.AuxRate + '_'
                  }
                });
              })
              
              if(ruleType == 5) {
                goodsIdStr = goodsIdStr.substring(0, goodsIdStr.length - 1)
                auxRateStr = auxRateStr.substring(0, auxRateStr.length - 1)
                goods_list.push({
                  productId: productId,
                  goodsId: productId + '_' + goodsIdStr,
                  num: rule.Multiple, 
                  radix: auxRateStr,
                });
              }
              
            });
          });
        }
        //设置缓存
        GoodsNumCache.init(goods_list);
        if (callback != undefined && typeof(callback) == "function") {
          callback(source);
        }
      } else {
        util.alert(res.Message);
      }
    }, "3.0");
  },
  /**
   * 加载购物车促销信息
   * @param {String} AreaId 地区id（开启地区匹配仓库）
   */
  loadPromotions: function(source, cart_dic, AreaId, callback) {
    var entity = authorize.getEntity();
    var goodsIds = [],
      sellers = [],
      goods_dic = cart_dic.goods_dic;
    for (var key in goods_dic) {
      goodsIds.push(key);
    }
    source.map(function(item) {
      sellers.push(item.Id);
    });
    var param = {
      fkids: sellers.join(","),
      goodsIds: goodsIds.join(","),
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKFlag: 2,
      AreaId: AreaId
    };
    util.post("order.cart.promotions", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          res.Content = cart.promotionsSorting(res.Content)
          cart.parsePromotion(source, goods_dic, cart_dic.rule_dic, res.Content)
          if (callback != undefined && typeof (callback) == "function") {
            callback(source);
          }
        }
      }
      else if (res.Code == api.timeoutCode){
        if (callback != undefined && typeof (callback) == "function") {
          callback(source);
        }
      }
    }, "3.0", null, false);
  },
  /**
   * 解析促销信息 
   * */
  parsePromotion: function(source, goods_dic, rule_dic, proms) {
    for(let i = 0; i < source.length; i++) {
      var key = "2_"+source[i].Id;
      source[i].Promotions = proms[key];
    }
    for (var key in proms) {
      var prom = proms[key];
      if (prom != null){
        for (var pi = 0; pi < prom.length; pi++) {
          var p = prom[pi];
          var goodsIds = p.GoodsIds;
          if (p.PromotionType == 1) {
            //单品
            var arry = [];
            if(goodsIds.length>0){
              arry = goodsIds.split(",");
            }
            for (var i = 0; i < arry.length; i++) {
              var goodsId = arry[i];
              var index_goods = goods_dic[goodsId];
              if (index_goods == undefined || index_goods.length != 4) {
                continue;
              }
              var goodsIndex = 0;
              for(let a = 0; a < source.length; a++) {
                let pRules = source[a].PromotRules
                for(let b = 0; b < pRules.length; b++) {
                  if(pRules[b].RuleType != 5) {
                    let prods = pRules[b].Products
                    for(let c = 0; c < prods.length; c++) {
                      let goods = prods[c].Goods
                      for(let d = 0; d < goods.length; d++) {
                        if(goods[d].GoodsId == goodsId) {
                          // 当特价商品参与活动时也需要进行相关计算(goods[d].DiscountType == 2 && goods[d].CanPartakePromotions == 1)
                          if ((goods[d].DiscountType != 2 || (goods[d].DiscountType == 2 && goods[d].CanPartakePromotions == 1)) && goods[d].DiscountType != 5) {
                            // 当单品促销商品存在多个促销活动时，只取第一个促销信息
                            // 已经有Promotion信息就不再用后面的覆盖了
                            if (isEmpty(goods[d].Promotion)) {
                              goods[d].Promotion = JSON.parse(JSON.stringify(p));
                              goods[d].RuleId = p.Id;
                              //单品促销只有第一条记录才显示促销信息
                              goods[d].isShowMark = goodsIndex == 0;
                              if(p.EnableSkuMode == 1 && goods[d].Promotion){
                                goods[d].Promotion.PromotLadder = p.PromotLadder.filter(e => e.GoodsId == goodsId)
                              }
                            }
                            goodsIndex ++;
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          } else {
            //多品
            var index_dic = rule_dic[p.Id];
            if (index_dic == undefined || index_dic.length != 2) {
              continue;
            }
            var item = source[index_dic[0]].PromotRules[index_dic[1]];
            item.Promotion = p;
          }
        }
      }
    }
  },

  /**
   * [calacPromotion 计算促销价格]
   * @param  {[type]}   dis   [促销信息]
   * @param  {type} gp [goods]
   */
  calacPromotion: function(dis, gp) {
    // 处理各种促销优惠
    if (dis && gp) {
      var promotLadder = dis.PromotLadder;
      var price = gp.originalPrice; //获取原价
      for (var i = 0; i < promotLadder.length; i++) {
        var multiple = 0;
        var originalQuantity = promotLadder[i].PromotUnitType == 2 ? gp.aux_quantity : gp.sum_quantity;
        switch (dis.DiscountMode) {
          case 1:
            if (dis.DiscountCalcType == 1) {
              multiple = parseInt(gp.price / promotLadder[i].MinimumValue);
            }
            if (price >= promotLadder[i].MinimumValue) {
              if (multiple == 0)
                gp.price = price - promotLadder[i].DiscountValue;
              else
                gp.price = price - (promotLadder[i].DiscountValue * multiple);
            }
            break;

          case 2:
            if (price >= promotLadder[i].MinimumValue) {
              gp.price = price * promotLadder[i].DiscountValue;
            }
            break;

          case 4:
            if (dis.DiscountCalcType == 1) {
              multiple = parseInt(originalQuantity / promotLadder[i].MinimumValue);
            }
            if (originalQuantity >= promotLadder[i].MinimumValue) {
              if (multiple == 0)
                gp.price = price - promotLadder[i].DiscountValue;
              else
                gp.price = price - (promotLadder[i].DiscountValue * multiple);
              // 优惠后的价格小于0，则直接为0
              if (gp.price < 0) {
                  gp.price = 0
              }
            }
            break;

          case 5:
            if (originalQuantity >= promotLadder[i].MinimumValue) {
              gp.price = price * promotLadder[i].DiscountValue;
              // 优惠后的价格小于0，则直接为0
              if (gp.price < 0) {
                gp.price = 0
              }
            }
            break;
          case 7:
            // 单品满降，减去需要降的金额
            if (originalQuantity >= promotLadder[i].MinimumValue) {
              let originalQuantity = promotLadder[i].PromotUnitType == 2 ? gp.aux_quantity : gp.sum_quantity
              gp.price = price -  originalQuantity * promotLadder[i].DiscountValue;
              if (gp.price < 0) {
                gp.price = 0
              }
            }
            break;
        }
        //自动叠加
        if (dis.DiscountCalcType == 1) break;
      }
    }
    return gp;
  },
  /**
   * [loadGifts 加载购物车赠送信息]
   * @param  {[type]}   source   [数据源]
   * @param  {Function} callback [回调函数]
   */
  loadGifts: function(source, cart_dic, callback) {
    var entity = authorize.getEntity();
    var sellers = [],
      product_arr = [],
      product_dic = cart_dic.product_dic;
    for (var key in product_dic) {
      product_arr.push(key);
    }
    for (var i = 0; i < source.length; i++) {
      sellers.push(source[i].Id);
    }
    var param = {
      fkids: sellers.join(","),
      productIds: product_arr.join(","),
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKFlag: 2
    };
    util.post("order.cart.gifts", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          //解析赠品
          cart.parseGifs(source, product_dic, res.Content);
          var reponse = source
          callback(source);

        }
      }
    }, "3.0", null, false);
  },
  /**
   * *解析赠品**
   * * */
  parseGifs: function(source, product_dic, proms) {
    for (var key in proms) {
      var prom = proms[key];
      for (var pi = 0; pi < prom.length; pi++) {
        var index_dic = product_dic[prom[pi].PriProductId];
        if (index_dic == undefined) {
          continue;
        }
        let productArray = [];
        for(var i=0;i<source.length;i++){
          var rule = source[i].PromotRules;
          for(var r=0;r<rule.length;r++){
            var pro=rule[r].Products;
            for(var p=0;p<pro.length;p++){
              // if(rule[r].RuleType != 5){
                if(pro[p].ProductId == prom[pi].PriProductId){
                  productArray.push(pro[p]);
                }
              // }
            }
          }
        }
        productArray.map((product)=>{
          for (var k = 0; k < product.Goods.length; k++) {
            product.Goods[k].gift.push({
              name: "赠品",
              info: prom[pi].Name,
              num: prom[pi].Quantity
            });
  
          }
        })
      }
    }
  },
  /**
   * [loadCoupons 加载优惠卷]
   * @param  {[type]}   source   [数据源]
   * @param  {Function} callback [回调函数]
   */
  loadCoupons: function(source, cart_dic, callback) {
    var entity = authorize.getEntity();
    var sellers = [],
      product_arr = [],
      product_dic = cart_dic.product_dic;
    for (var key in product_dic) {
      product_arr.push(key);
    }
    for (var i = 0; i < source.length; i++) {
      sellers.push(source[i].Id);
    }
    var param = {
      fkids: sellers.join(","),
      productIds: Array.isArray(product_arr[0]) ? product_arr[0].join(",") : product_arr[0],
      ProprietorId: app.dns.proprietorId,
      UserId: entity.fkId,
      FKFlag: 2
    };
    util.post("order.cart.coupons", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content["2_" + sellers.join("")] || []);

        }
      }
    }, "3.0", null, false);
  },
  /**
   * [delCart 购物车中删除货品]
   * @param  {[type]}   source   [数据源]
   * @param  {[type]}   goodsId   [货品id]
   * @param  {[dic]}    cart_dic  [购物车键值对]]
   * @param  {Function} callback [回调函数]
   */
  delSingleCart:function(source, goodsIds,CartName, callback){
    var entity = authorize.getEntity();
      var param = {
      CartIds: goodsIds,
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity ? entity.fkId : 0,
      FKFlag: entity == undefined || entity.fkFlag == 1 ? 2 : 1,
      ProprietorId: app.dns.proprietorId
    };
    var name = '是否确认删除'+CartName+'商品';
    util.confirm(function() {
      util.post("order.cart.delete", param, function(res) {
        res = res.data;
        if (res.Success) {
          for(var i = 0;i < source.length; i++){
            var rule = source[i].PromotRules;
            for(var j = 0;j < rule.length; j++){
              var pro = rule[j].Products;
              for(var p = 0; p < pro.length; p++){
                var good = pro[p].Goods;
                for(var g = 0;g < good.length; g++){
                  if(good[g].Id == goodsIds){
                    good.splice(g,1)
                  }
                }
              }
            }
          }
          util.success("删除成功", function() {
            //回调
            if (callback != undefined && typeof(callback) == "function") {
              callback(source);
              //更新购物车数量
              cart.get_cart_count();
            }
          });

        } else {
          util.tips("删除失败" + res.Message);
        }
      }, "3.0", null, false)
    }, null, name, "确认删除")
  },
  delCart: function(source, goodsIds, CartName, callback) {
    var entity = authorize.getEntity();
    var cartIds = goodsIds
    var param = {
      CartIds: cartIds.join(","),
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity ? entity.fkId : 0,
      FKFlag: entity == undefined || entity.fkFlag == 1 ? 2 : 1,
      ProprietorId: app.dns.proprietorId
    };
    var name = '是否确认删除'+CartName+'商品';
    util.confirm(function() {
      util.post("order.cart.delete", param, function(res) {
        res = res.data;
        if (res.Success) {
          try {
            goodsIds.map(function (goodsId) {
              //删除键
              cart.delSource(source, goodsId);
              GoodsNumCache.del(goodsId);
            })
          } catch (e) {
            console.log("删除键"+e);
          }
          util.success("删除成功", function() {
            //回调
            if (callback != undefined && typeof(callback) == "function") {
              callback(source);
              //更新购物车数量
              cart.get_cart_count();
            }
          });

        } else {
          util.tips("删除失败" + res.Message);
        }
      }, "3.0", null, false)
    }, null, name, "确认删除")
  },
  delSource: function(source, goodsId) {
    source.map(function(seller, i) {
      seller.PromotRules.map(function(rule, j) {
        rule.Products.map(function(p, k) {
          p.Goods.map(function(g, l) {
            if (g.GoodsId == goodsId) {
              if (p.Goods.length == 1) {
                rule.Products.splice(k, 1);
                if (rule.RuleId > 0 && rule.Products.length == 0) {
                  seller.PromotRules.splice(j, 1);
                }
              } else {
                p.Goods.splice(l, 1);

              }
              return;
            }
          });
        });
      });
    });
  },
  /**
   * [removeGoods 重新设置索引
   * @param  {[type]}   source   [数据源]
   * @param  {[type]}   cartId   [购物车id]
   */
  reset_cart_dic: function(source) {
    var goods_dic = {},
      product_dic = {},
      rule_dic = {},
      array = [];
    source.map(function(seller, i) {
      seller.PromotRules.map(function(rule, j) {
        rule_dic[rule.RuleId] = [i, j];
        rule.Products.map(function(p, k) {
          array.push([i, j, k]);
          product_dic[p.ProductId] = array;
          p.Goods.map(function(g, l) {
            goods_dic[g.GoodsId] = [i, j, k, l];
          });
        });
      });
    });
    return {
      product_dic: product_dic,
      goods_dic: goods_dic,
      rule_dic: rule_dic
    };
  },
  /**
   * [update_cart_num 更新购物车数量]
   * @param  {[object]}   source   [数据源]
   * @param  {[int]}   goodsId   [goodsid]
   * @param  {[float]}   num      [数量]
   * @param  {[dic]]} cart_dic 购物车的键对
   * @param  {Function} callback [回调函数]
   */
  update_cart_num: function (source, goodsId, num, quantityDigits,callback, error_callback) {
    var entity = authorize.getEntity();
    var product={};
    var goods={};
    for(var i = 0;i < source.length; i++){
      var rule = source[i].PromotRules;
      for(var j = 0;j < rule.length; j++){
        let ruleId = null
        if(rule[j].RuleType == 5){
          ruleId = rule[j].RuleId
        } else {
          ruleId = -1
        }
        var pro = rule[j].Products;
        for(var p = 0; p < pro.length; p++){
          var good = pro[p].Goods;
          for(var g = 0;g < good.length; g++){
            var item = good[g];
            if(item.Id == goodsId){
              item.Quantity = num;
              item.AuxQty = num;
              if (good.DiscountType != 5 && good.length>1) {
                var otherUnitQuantity = 0;
                for (let n = 0; n < good.length; n++) {
                    var child = good[n];
                    if (child.GoodsId==item.GoodsId&&child.DiscountType!=5&&child.AuxRate!=item.AuxRate&&child.AuxQty>0) {
                        otherUnitQuantity += (child.AuxQty || 0) * (child.AuxRate || 1);
                    }
                }
                item.BuyLowerLimit = item.SBuyLowerLimit > 0 && item.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", item.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
                item.BuyUpperLimit = item.SBuyUpperLimit > 0 && item.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", item.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
                item.Stock = item.SStock > 0 && item.SStock > otherUnitQuantity ? util.keepDecimal("ceil", item.SStock - otherUnitQuantity, quantityDigits) : 0;
              }
              goods = item;
              goods.ids = item.Id
              goods.ruleIds = ruleId
              product = pro[p];
            }
          }
        }
      }
    }
    cart.displayPrice(goods);
      if (callback != undefined && typeof(callback) == "function") {
        callback(source);
      }
//     if(ruleType !== 5) {
      
      var param = {
        CartIds: goodsId,
        Token: entity && entity.manager ? entity.manager.Token : '',
        FKId: source[0].Id,
        FKFlag: entity == undefined || entity.fkFlag == 1 ? 2 : 1,
        UserId: entity ? entity.fkId : 0,
        ProductId: product.ProductId,
        GoodsId: goods.GoodsId,
        SpecValue: goods.SpecValue,
        DiscountType: goods.DiscountType,
        DiscountId: goods.DiscountId,
        AuxRate: goods.AuxRate,
        AuxQty: num,
        Quantity: util.keepDecimal("ceil", (num * goods.AuxRate), quantityDigits) ,
        AuxUnit: goods.AuxUnit,
        ProprietorId: app.dns.proprietorId
      };
      // console.log(param,'=======param');
      util.post("order.cart.change", param, function(res) {
        res = res.data;
        if (res.Success) {
          //添加修改键
          GoodsNumCache.add(param.ProductId, param.GoodsId, param.AuxQty, param.AuxRate);
        } else {
          //util.tips("操作失败" + res.Content);
  
        }
  
      }, "3.0",null,false);
    // }
  },
  /**
   * 判断数量
   */
  judge_quantity: function(g, q, zerostockbuy) {

    var msg = "";

    if (zerostockbuy == undefined) zerostockbuy = 0;

    //验证购买限制
    if (q * g.AuxRate < g.BuyLowerLimit && g.DiscountType != 5) {

      q = Math.ceil(g.BuyLowerLimit / g.AuxRate);
      g.Quantity = q;
      msg = "最少购买" + q + g.AuxUnit;
    } else if (g.BuyUpperLimit > 0 && q * g.AuxRate > g.BuyUpperLimit && g.DiscountType != 5) {
      if (g.DiscountType == 2 && g.ExceedLimitOriginalPriceBuy == 1) {
        // 当开启特价商品超限加购时，不校验限制购买数量BuyUpperLimit，而是校验商品库存Stock
        if (q * g.AuxRate > g.Stock) {
          q = Math.floor(g.Stock / g.AuxRate);
          g.Quantity = q;
          msg = "最多可购" + q + g.AuxUnit;
        }
      } else {
        q = Math.floor(g.BuyUpperLimit / g.AuxRate);
        g.Quantity = q;
        msg = "最多可购" + q + g.AuxUnit;
      }
    }
    //未开启零库时，验证库存数量
    if (zerostockbuy == 0 && q * g.AuxRate > g.Stock && g.DiscountType != 5) {

      q = Math.floor(g.Stock / g.AuxRate);
      g.Quantity = q;
      msg = "最多可购" + q + g.AuxUnit;
    }
    if (msg.length > 0) {
      util.tips(msg);
    }
    return msg.length > 0;
  },
  /**
   * [selectAllStatus 全选状态]
   * @param  {[type]}   source   [数据源]
   * @param  {[bool]}   isChecked   [是否选中]
   * @param  {[dic]}   cart_dic   [购物车键值对]
   * @param  {Function} callback [回调函数]
   */
  selectAllStatus: function(source, isChecked, callback, error_callback) {
    var carts_arr = [],
      list = [];
    source.map(function(seller, i) {
      seller.PromotRules.map(function(rule, j) {
        rule.Products.map(function(p, k) {
          p.Goods.map(function(g, l) {
            //失效-没有库存状态
            if (g.Shelved == 1 && p.PurchasePower && !((g.Stock <= 0 || g.Stock < g.BuyLowerLimit) && p.ZeroStockBuy == 0)) {
              if(g.IsBuy==1){
                carts_arr.push(g.Id);
                list.push(g);
              }
            }
          });
        });
      });
    });
    cart.updateCartCheckStatus(source, list, carts_arr.join(','), isChecked, callback, error_callback);
  },
  /**
   * [singleCheckStatus 全选状态]
   * @param  {[type]}   source   [数据源]
   * @param  {[int]}   goodsId   [数据源]
   * @param  {[bool]}   isChecked   [是否选中]
   * @param  {[dic]}   cart_dic   [购物车键值对]
   * @param  {Function} callback [回调函数]
   */
  singleCheckStatus:function(source,id,isChecked,callback,error_callback){
    for(var i = 0;i < source.length; i++){
      var rule = source[i].PromotRules;
      for(var j = 0;j < rule.length; j++){
        var pro = rule[j].Products;
        for(var p = 0; p < pro.length; p++){
          var good = pro[p].Goods;
          for(var g = 0;g < good.length; g++){
            if(good[g].Id == id){
              good[g].IsChecked = isChecked;
            }
          }
        }
      }
    }
    if (callback != undefined && typeof(callback) == "function") {
      callback(source);
    }
    var entity = authorize.getEntity();
    var param = {
      CartIds: id,
      IsChecked: isChecked,
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity ? entity.fkId : 0,
      FKFlag: entity == undefined || entity.fkFlag == 1 ? 2 : 1,
      ProprietorId: app.dns.proprietorId
    };
    // console.log(param,'=========param');
    util.post("order.cart.updischecked", param, function (res) {
      res = res.data;
      if (res.Success) {

      } else {
        util.alert("操作失败" + res.Message);
        if (error_callback != undefined && typeof (error_callback) == "function") {
          error_callback(source);
        }

      }
    }, "3.0", null, false);
    
  },
  /**
   * [updateCartCheckStatus 更新购物车选中状态]
   * @param  {[type]}   source   [数据源]
   * @param  {[type]}   cartId   [购物车id]
   * @param  {Function} callback [回调函数]
   */
  updateCartCheckStatus: function(source, list, cartIds, isChecked, callback, error_callback) {
    // console.log(list,'=========1');
    var entity = authorize.getEntity();
    //设置选中状态
    for (var m = 0; m < list.length; m++) {

      list[m].IsChecked = isChecked;
    }
    //回调
    if (callback != undefined && typeof (callback) == "function") {
      callback(source);
    }
    
    var param = {
      CartIds: cartIds,
      IsChecked: isChecked,
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity ? entity.fkId : 0,
      FKFlag: entity == undefined || entity.fkFlag == 1 ? 2 : 1,
      ProprietorId: app.dns.proprietorId
    };
    // console.log(param,'=========param');
    util.post("order.cart.updischecked", param, function (res) {
      res = res.data;
      if (res.Success) {

      } else {
        util.alert("操作失败" + res.Message);
        if (error_callback != undefined && typeof (error_callback) == "function") {
          error_callback(source);
        }

      }
    }, "3.0", null, false);

    
  },
  /**
   * [caculate_info 计算信息]
   * @param  {[type]}   source   [数据源]
   * @param {Number} priceDigits 价格位数
   * @param {Number} quantityDigits 数量位数
   */
  caculate_info: function(source, priceDigits = 2, quantityDigits = 2) {
    var result = { prices: 0, integral: 0, quantity: 0, discount: 0, money: 0 };
    let selectedGoods = this.getAllSelectedGood(source)
    for (var i = 0; i < source.length; i++) {
      let seller = source[i];
      // 记录当前一个店铺的价格信息
      let selPrice = {
        prices: parseFloat(0),
        integral: parseFloat(0),
        quantity: parseFloat(0),
        discount: parseFloat(0),
        money: parseFloat(0),
      };
      for (var j = 0; j < seller.PromotRules.length; j++) {
        let rule = seller.PromotRules[j];
        if (rule.RuleType == 5 && rule.RuleId > 0) {
          //组合套餐
          let priceCount = 0, integralCount = 0, qtyCount = 0;
          if(rule.Checked === 1) {
            let products = rule.Products || [];
            for(let k = 0; k < products.length; k++) {
              let goods = products[k].Goods;
              let itemPrice = cart.getItemPrice(goods);
              let itemQty = cart.getGoodsNum(goods);
              priceCount += itemPrice.price;
              integralCount += itemPrice.integral;
              qtyCount += itemQty;
            }
            selPrice.prices += priceCount * Number(rule.Multiple);
            selPrice.integral += integralCount * Number(rule.Multiple);
            selPrice.quantity += qtyCount * Number(rule.Multiple);
            selPrice.money += priceCount * Number(rule.Multiple);
          }
        }else if (rule.RuleId > 0) {
          //多品促销
          var opt = cart.caculate_multi_spect(rule);
          //促销信息
          rule.info = cart.parsePromotionInfo(rule.Promotion, opt, {}, selectedGoods);
          if (opt){
            selPrice.prices += opt.originalPrice;
            selPrice.integral += opt.integral;
            selPrice.quantity += opt.quantity;
            selPrice.money += opt.price;
          }
        } else {
          //单品促销
          for (var k = 0; k < rule.Products.length; k++) {
            var p = rule.Products[k];
            let marketGoodsIds = [];
            for (var l = 0; l < p.Goods.length; l++) {
              var g = p.Goods[l];
              //计算促销金额
              var opt = cart.caculate_single_spect(g, p);
              //绑定促销信息
              g.info = cart.parsePromotionInfo(g.Promotion, opt, g);
              if (g.Promotion && g.Promotion.Id > 0) {
                if (g.IsChecked  && marketGoodsIds.indexOf(g.GoodsId) == -1) {
                  marketGoodsIds.push(g.GoodsId);
                }else{
                  opt.price = 0;
                  opt.integral = 0;
                  opt.originalPrice = 0;
                }
              }
              //只有选中才计算
              if (g.IsChecked&&g.IsBuy) {
                if (g.IsDeduction) { // 是否允许抵扣, 计算时只处理现金
                  selPrice.money += opt.price;
                } else {
                  if (g.SaleMode == 0) { // 现金
                    selPrice.money += opt.price;
                  } else if (g.SaleMode == 1) { //积分
                    selPrice.integral += opt.integral;
                  } else { //  现金 + 积分
                    selPrice.money += opt.price;
                    selPrice.integral += opt.integral;
                  }
                }
                selPrice.quantity += opt.quantity;
                selPrice.prices += opt.originalPrice;
              }
            }
          }
        }
      }
      if (seller.Promotions&&seller.Promotions.length>0) {
        let processedGoods = {} // 已处理过数据的商品信息
        for (var p = 0; p < seller.Promotions.length; p++) {
          let prom = seller.Promotions[p];
          let goodsIds = prom.GoodsIds || '';
          prom.DiscountAmount = 0;
          if (goodsIds != '') {
            var arry = goodsIds.split(',');


            var sellerPrice = {
              price: parseFloat(0),
              integral: parseFloat(0),
              originalPrice: parseFloat(0),
              quantity: 0, // 加购单位数量
              sum_quantity: parseFloat(0), // 基础单位数量
              aux_quantity: parseFloat(0), // 销售单位数量
            }
            for (var i = 0; i < arry.length; i++) {
              var goodsId = arry[i];
              var rulePrice = {
                price: parseFloat(0),
                integral: parseFloat(0),
                originalPrice: parseFloat(0),
                quantity: 0, // 加购单位数量
                sum_quantity: parseFloat(0), // 基础单位数量
                aux_quantity: parseFloat(0), // 销售单位数量
              }
              for (var j = 0; j < seller.PromotRules.length; j++) {
                let rule = seller.PromotRules[j];
                for (var k = 0; k < rule.Products.length; k++) {
                  var product = rule.Products[k];
                  for (var l = 0; l < product.Goods.length; l++) {
                    var g = product.Goods[l];
                    // 当为特价商品并且参与活动时也需要进行相关计算(g.DiscountType == 2 && g.CanPartakePromotions == 1)
                    let key = `${g.Id}_${g.GoodsId}`
                    if (processedGoods[key]) {
                      // 已处理过促销的商品数据，不再处理其他的促销活动
                    } else if (g.IsBuy==1 &&g.IsChecked && goodsId == g.GoodsId && (g.DiscountType != 2 || (g.DiscountType == 2 && g.CanPartakePromotions == 1)) && g.DiscountType != 5) {
                      var quantity = g.AuxQty || 0;
                      // 计算总价
                      rulePrice.price += util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2);
                      rulePrice.originalPrice += util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2);
                      rulePrice.integral += util.keepDecimal("ceil", (g.pay_integral || 0) * quantity, 0);
                      rulePrice.quantity += quantity;
                      rulePrice.sum_quantity += util.keepDecimal("ceil", quantity * (g.AuxRate || 1), 4);
                      rulePrice.aux_quantity += util.keepDecimal("ceil", quantity * (g.AuxRate || 1) / (g.DefaultUnitTranslated || 1), 4);
                      processedGoods[key] = true
                    }
                  }
                }
              }
              sellerPrice.price += rulePrice.price;
              sellerPrice.originalPrice += rulePrice.originalPrice;
              sellerPrice.integral += rulePrice.integral;
              sellerPrice.quantity += rulePrice.quantity;
              sellerPrice.sum_quantity += rulePrice.sum_quantity;
              sellerPrice.aux_quantity += rulePrice.aux_quantity;
              //单品促销计算
              if (prom.PromotionType==1) {
                var opt = cart.calacPromotion(prom, rulePrice);
                prom.DiscountAmount += (opt.originalPrice - opt.price > 0 ? opt.originalPrice - opt.price : 0);
              }
            }
            //组合促销计算
            if (prom.PromotionType==2) {
              let diff = this.getSkuDifference(prom, selectedGoods)
              var opt = cart.calacPromotion(prom, sellerPrice);
              // 组合促销，当选择的商品满足最少sku和必买商品时，才计算促销减免的金额
              if (diff.skuDifference == 0 && diff.mustBuyDifference == 0) {
                prom.DiscountAmount += (opt.originalPrice - opt.price > 0 ? opt.originalPrice - opt.price : 0);
              }
            }
          }
          selPrice.discount += prom.DiscountAmount;
        }
      }
      result.prices += selPrice.prices;
      result.integral += selPrice.integral;
      result.quantity += selPrice.quantity;
      result.discount += selPrice.discount;
      result.money += (selPrice.prices - selPrice.discount);
    }
    result.discount = Math.round(result.discount * Math.pow(10, priceDigits)) / Math.pow(10, priceDigits)
    if (result.discount > 0) {
      if (result.discount >= result.prices) {
        result.discount = result.prices
        result.money = 0
      } else {
        result.money = calculation(result.prices, '-', result.discount)
      }
    }
    return result;
  },
  /**
   * 获取所有被选中的商品信息
   * @param {Array} source 购物车数据
   */
  getAllSelectedGood (source = []) {
    let result = []
    for (let i = 0; i < source.length; i++) {
      let PromotRules = source[i].PromotRules || []
      for (let j = 0; j < PromotRules.length; j++) {
        let Products = PromotRules[j].Products || []
        for (let k = 0; k < Products.length; k++) {
          let Goods = Products[k].Goods || []
          for (let x = 0; x < Goods.length; x++) {
            if (Goods[x].IsChecked) {
              result.push(Goods[x])
            }
          }
        }
      }
    }
    return result
  },
  /**
   * 返回选中商品的转换为基础单位后的id和数量
   */
  getSelectedGoodCount (selectedGoods = []) {
    let obj = {}
    for (let i = 0; i < selectedGoods.length; i++) {
      let id = selectedGoods[i].GoodsId
      let AuxQty = selectedGoods[i].AuxQty
      let AuxRate = selectedGoods[i].AuxRate
      if (!obj[id]) {
        obj[id] = {
          GoodsId: id,
          count: AuxQty * AuxRate
        }
      } else {
        obj[id].count += AuxQty * AuxRate
      }
    }
    return Object.values(obj)
  },
  /**
   * 组合促销获取差的sku数和必卖商品数
   */
  getSkuDifference(prom, selectedGoods) {
    // 组合促销，计算是否满足必买商品规则和最少参与SKU数
    let promotionType = prom.PromotionType
    let skuDifference = 0 // 距离最少要购买的sku差多少种
    let mustBuyDifference = 0 // 距离满足必买商品数量差多少种
    if (promotionType == 2) {
      let MustBuyGoods = prom.MustBuyGoods || [] // 必买商品
      if (isEmpty(selectedGoods)) {
        skuDifference = prom.MinGoodsCount || 0
        mustBuyDifference = MustBuyGoods.length || 0
      } else {
        // 最少购买sku数
        if (prom.MinGoodsCount > 0) {
          let ids = prom.GoodsIds || ''
          ids = ids.split(',')
          let count = selectedGoods.filter((item) => {
            let id = item.GoodsId
            id = id.toString()
            if (ids.includes(id)) {
              return true
            }
            return false
          })
          // 合并goodsId相同的项
          count = count.map((item) => {
            return item.GoodsId
          })
          count = Array.from(new Set(count))
          skuDifference = prom.MinGoodsCount - count.length
          if (skuDifference < 0) {
            skuDifference = 0
          }
          skuDifference = skuDifference
        }
        // 必买商品
        if (MustBuyGoods.length > 0) {
          mustBuyDifference = MustBuyGoods.length
          selectedGoods = this.getSelectedGoodCount(selectedGoods)
          for (let i = 0; i < MustBuyGoods.length; i++) {
            for (let j = 0; j < selectedGoods.length; j++) {
              let item1 = MustBuyGoods[i]
              let item2 = selectedGoods[j]
              if (item1.GoodsId == item2.GoodsId) {
                let min = item1.MinBuyNum * item1.Translated
                // 选择的商品和必买商品换算基础单位后比较
                if (item2.count >= min) {
                  mustBuyDifference -= 1
                }
                continue
              }
            }
          }
          if (mustBuyDifference < 0) {
            mustBuyDifference = 0
          }
          mustBuyDifference = mustBuyDifference
        }
      }
    }
    return {
      skuDifference,
      mustBuyDifference
    }
  },
  getItemPrice(goods) {
    let price = {price: 0, integral: 0}
    if(goods === null || goods.length <= 0) {
      return price
    }
    for(let i = 0; i < goods.length; i++) {
      let g = goods[i];
      if(g.IsBuy==1){
      var quantity = g.AuxQty || 0;
      if(g.IsDeduction == 1 || g.SaleMode == 0 || g.SaleMode == 2){
        price.price += util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2);
      }
      if(g.IsDeduction != 1 && (g.SaleMode == 1 || g.SaleMode == 2)){
        price.integral += util.keepDecimal("ceil", (g.pay_integral || 0) * quantity, 0);
      }
    }
    }
    return price
  },
  getGoodsNum(goods){
    let quantity = 0
    if(goods === null || goods.length <= 0) {
      return quantity
    }
    for(let i = 0; i < goods.length; i++) {
      if(goods[i].IsBuy==1){
      quantity += goods[i].Quantity}
    }
    return quantity
  },
  /**计算每个货品小计 */
  caculateSubtotal(g){
    var quantity = g.AuxQty || 0;
    g.price_subtotal = util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2);
    g.pay_integral_subtotal = util.keepDecimal("ceil", (g.pay_integral || 0) * quantity, 0);
  },
  /**
   * 解析每一个规格的促销信息
   * @param {Object} goods 商品信息，用于解析展示商品数量的规格
   */
  parseSinglePromotionInfo: function(discountMode, promotionType, discountCalcType, currentLadder, gp, enableSkuMode, goods) {
    var tinfo = "";
    var tmp = "{0}{1}{2}，{3}{4}{5}{6}";
    var originalPrice = gp.originalPrice;
    var originalQuantity = currentLadder.PromotUnitType == 2 ? gp.aux_quantity : gp.sum_quantity
    var opt = {
      name: "",
      info: "",
      id: currentLadder.Id,
      value: currentLadder.DiscountValue,
      discountmode: discountMode,
      unit: ""
    };
    // 赠送商品
    let unit = '' // 商品单位
    let giftUnit = '' // 赠送商品的单位
    if (currentLadder.Gifts && currentLadder.Gifts != "") {
      if (enableSkuMode == 1) {
        // 按商品单独设置，直接取返回的商品单位
        giftUnit = currentLadder.GiftsUnit || ''
      } else {
        if (!goods) {
          goods = {}
        }
        // 基础单位
        if (currentLadder.GiftsUnitType == 1) {
          giftUnit = goods.Unit || ''
        } else {
          // 销售单位
          giftUnit = goods.DefaultUnit || ''
        }
      }
      // 送本品
      if (currentLadder.GiftType == 1) {
        if (currentLadder.GiftsNum > 0) {
          tinfo = '，送本品' + currentLadder.GiftsNum + giftUnit
        } else {
          tinfo = '，送本品'
        }
      } else {
        if (currentLadder.GiveMethod == 1) {
          // 选赠品
          tinfo += `，任选${currentLadder.GiveCount || ''}种赠品`
        } else {
          // 送赠品
          // GiftsNumTotal：赠品总数
          tinfo = '，送赠品数量'
          tinfo += currentLadder.GiftsNumTotal || ''
        }
      }
    }
    if (enableSkuMode == 1) {
      unit = currentLadder.Unit || ''
    } else {
      if (!goods) {
        goods = {}
      }
      // 非组合促销才需要单位
      if (promotionType == 1) {
        if (currentLadder.PromotUnitType == 2) {
          // 销售单位
          unit = goods.DefaultUnit || ''
        } else {
          // 基础单位
          unit = goods.Unit || ''
        }
      } else {
        // 组合促销
        if (currentLadder.PromotUnitType == 2) {
          unit = '销售单位'
        } else {
          unit = '基础单位'
        }
      }
    }
    if (currentLadder.Coupons && currentLadder.Coupons != "") {
      tinfo += "，送优惠劵";
    }
    if (currentLadder.FreeFreight == 1) {
      tinfo += "，免邮";
    }
    // 商品满的数量
    let minimumValue = enableSkuMode == 1 && discountMode == 6 ? parseFloat(currentLadder.MinimumValue * (currentLadder.Translated || 1), 0) : parseFloat(currentLadder.MinimumValue, 0)
    switch (discountMode) {
      case 1:
        opt.name = "满减";
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "金额" + (discountCalcType == 1 ? "每" : "") + "满", parseFloat(currentLadder.MinimumValue).toFixed(2), "元", "立减", parseFloat(currentLadder.DiscountValue).toFixed(2), "元", tinfo);
        opt.difference = currentLadder.MinimumValue - originalPrice;
        break;
      case 2:
        opt.name = "打折";
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "金额" + (discountCalcType == 1 ? "每" : "") + "满", parseFloat(currentLadder.MinimumValue).toFixed(2), "元", "打", parseFloat(currentLadder.DiscountValue * 10).toFixed(2), "折", tinfo);
        opt.difference = currentLadder.MinimumValue - originalPrice;
        break;
      case 3:
        opt.name = "满赠";//优惠改满赠
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "金额" + (discountCalcType == 1 ? "每" : "") + "满", parseFloat(currentLadder.MinimumValue).toFixed(2), "元", tinfo.replace("，", ""), "", "", "");
        opt.difference = currentLadder.MinimumValue - originalPrice;
        break;
      case 4:
        opt.name = "满减";
        opt.difference = minimumValue - originalQuantity
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "数量" + (discountCalcType == 1 ? "每" : "") + "满", currentLadder.MinimumValue + unit, "", "立减", parseFloat(currentLadder.DiscountValue).toFixed(2), "元", tinfo);
        opt.unit = unit
        break;
      case 5:
        opt.name = "打折";
        opt.difference = minimumValue - originalQuantity
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "数量" + (discountCalcType == 1 ? "每" : "") + "满", currentLadder.MinimumValue + unit, "", "打", parseFloat(currentLadder.DiscountValue * 10).toFixed(2), "折", tinfo);
        opt.unit = unit
        break;
      case 6:
        opt.name = "满赠";//优惠改满赠
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "数量" + (discountCalcType == 1 ? "每" : "") + "满", currentLadder.MinimumValue + unit, "", tinfo.replace("，", ""), "", "", "");
        opt.difference = minimumValue - originalQuantity
        if (enableSkuMode == 1 && currentLadder.Translated > 0) {
          opt.difference = util.keepDecimal("ceil", opt.difference / currentLadder.Translated, 4)
        }
        opt.unit = unit
        break;
      case 7:
        opt.name = "满降";
        opt.difference = minimumValue - originalQuantity
        opt.info = tmp.format((promotionType == 1 ? "单品" : "商品组合") + "数量" + (discountCalcType == 1 ? "每" : "") + "满", currentLadder.MinimumValue + unit, "", "单价立降", parseFloat(currentLadder.DiscountValue).toFixed(2), "元", tinfo);
        opt.unit = unit
        break;
    }
    return opt;
  },
  /*
   *解析促销信息
   * @param {Object} goods 商品信息
   * @param {Array} selectedGoods 所有被选中的商品
   */
  parsePromotionInfo: function(prom, gp, goods, selectedGoods = []) {
    var opt = null;
    if (prom) {
      var originalPrice = gp.originalPrice;
      var promotLadder = prom.PromotLadder,
        discountMode = prom.DiscountMode,
        promotionType = prom.PromotionType,
        enableSkuMode = prom.EnableSkuMode;
      var length = promotLadder.length;
      var lastLadder = length > 0 ? promotLadder[promotLadder.length - 1] : undefined;
      var lastMinValue = lastLadder != undefined ? (discountMode == 6 && enableSkuMode == 1 ? lastLadder.MinimumValue * lastLadder.Translated : lastLadder.MinimumValue) : 0;
      let lastQuantity = lastLadder != undefined && lastLadder.PromotUnitType == 2 ? gp.aux_quantity : gp.sum_quantity;
      if(prom.DiscountCalcType == 1) length = 1;
      let index = -1 // 当前命中的促销规则index
      for (var i = 0; i < length; i++) {
        var currentLadder = promotLadder[i], 
        nextLadder = promotLadder[i >= (promotLadder.length - 1) ? (promotLadder.length - 1) : (i + 1)],
        originalQuantity = currentLadder.PromotUnitType == 2 ? gp.aux_quantity : gp.sum_quantity;
        if (discountMode == 1 || discountMode == 2 || discountMode == 3) {
          if(originalPrice < currentLadder.MinimumValue){
            opt = cart.parseSinglePromotionInfo(discountMode, promotionType, prom.DiscountCalcType, currentLadder, gp, enableSkuMode, goods);
            index = i - 1
            break;
          }else if(originalPrice < nextLadder.MinimumValue){
            opt = cart.parseSinglePromotionInfo(discountMode, promotionType, prom.DiscountCalcType, nextLadder, gp, enableSkuMode, goods);
            index = i
            break;
          }else{
            opt = cart.parseSinglePromotionInfo(discountMode, promotionType, prom.DiscountCalcType, currentLadder, gp, enableSkuMode, goods);
            index = i
          }
        }else{
          // 比对当前数量和对应数量时，先转换为同一单位
          let nextMinValue = ''
          let currentMinValue = ''
          if (discountMode == 6 && enableSkuMode == 1) {
            nextMinValue = nextLadder.MinimumValue * (nextLadder.Translated || 1)
            currentMinValue = currentLadder.MinimumValue * (currentLadder.Translated || 1)
          } else {
            nextMinValue = nextLadder.MinimumValue
            currentMinValue = currentLadder.MinimumValue
          }
          if(originalQuantity < currentMinValue){
            opt = cart.parseSinglePromotionInfo(discountMode, promotionType, prom.DiscountCalcType, currentLadder, gp, enableSkuMode, goods);
            index = i - 1
            break;
          }else if(originalQuantity < nextMinValue){
            opt = cart.parseSinglePromotionInfo(discountMode, promotionType, prom.DiscountCalcType, nextLadder, gp, enableSkuMode, goods);
            index = i
            break;
          }else{
            opt = cart.parseSinglePromotionInfo(discountMode, promotionType, prom.DiscountCalcType, currentLadder, gp, enableSkuMode, goods);
            index = i
          }
        }
      }
      if(!isEmpty(opt) && lastQuantity >= lastMinValue && prom.DiscountCalcType != 1){
        opt.difference = 0;
      }
      if (!isEmpty(opt)) {
        opt.promotionIndex = index
        opt.showChooseProductGift = false // 是否显示选赠品按钮
      }
      if (index !== -1) {
        if (promotLadder[index].GiveMethod == 1) {
          opt.showChooseProductGift = true
          opt.currentLadder = promotLadder[index]
        }
      }
      // 组合促销，计算是否满足必买商品规则和最少参与SKU数
      if (promotionType == 2) {
        let diff = this.getSkuDifference(prom, selectedGoods)
        opt.skuDifference = diff.skuDifference
        opt.mustBuyDifference = diff.mustBuyDifference
        if (opt.showChooseProductGift) {
          if (diff.skuDifference > 0 || diff.mustBuyDifference > 0) {
            // 如果sku数或者必买商品未满足条件，也不显示选赠品按钮
            opt.showChooseProductGift = false
          }
        }
      }
    }
    return opt;
  },
  /**
   * 计算单规格
   */
  caculate_single_spect: function(g, p) {
    var rulePrice = {
      price: parseFloat(0),
      integral: parseFloat(0),
      originalPrice: parseFloat(0),
      quantity: 0, // 加购单位数量
      sum_quantity: parseFloat(0), // 基础单位数量
      aux_quantity: parseFloat(0), // 销售单位数量
    }
    //计算单个货品小计
    cart.caculateSubtotal(g);
    if (g.Promotion && g.Promotion.Id > 0) {
      for (var l = 0; l < p.Goods.length; l++) {
        var gd = p.Goods[l];
        var quantity = gd.AuxQty || 0;
        if (gd.IsChecked && gd.Promotion && g.Promotion && gd.GoodsId == g.GoodsId && gd.Promotion.Id == g.Promotion.Id) {
          // 计算总价
          rulePrice.price += util.keepDecimal("ceil", (gd.sale_price || 0) * quantity, 2);
          rulePrice.originalPrice += util.keepDecimal("ceil", (gd.sale_price || 0) * quantity, 2);
          rulePrice.integral += util.keepDecimal("ceil", (gd.pay_integral || 0) * quantity, 0);
          rulePrice.quantity += quantity;
          rulePrice.sum_quantity += util.keepDecimal("ceil", quantity * (gd.AuxRate || 1), 4);
          rulePrice.aux_quantity += util.keepDecimal("ceil", quantity * (gd.AuxRate || 1) / (gd.DefaultUnitTranslated || 1), 4); // 计算默认销售单位数量
        }
      }
      rulePrice = cart.calacPromotion(g.Promotion, rulePrice);
    }else {
      var quantity = g.AuxQty || 0;
      rulePrice = {
        price: util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2),
        integral: util.keepDecimal("ceil", (g.pay_integral || 0) * quantity, 0),
        originalPrice: util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2),
        quantity: quantity,
        sum_quantity: util.keepDecimal("ceil", quantity * (g.AuxRate || 1), 4),
        aux_quantity: util.keepDecimal("ceil", quantity * (g.AuxRate || 1) / (g.DefaultUnitTranslated || 1), 4) // 计算默认销售单位数量
      }
    }
    return rulePrice;
  },
  /**
   * 计算多规格
   */
  caculate_multi_spect: function(rule) {
    if (!rule.Promotion || rule.Promotion.Id == 0) return false;
    var gPromotion = rule.Promotion;
    if (!gPromotion) return false;
    var rulePrice = {
      price: parseFloat(0),
      integral: parseFloat(0),
      originalPrice: parseFloat(0),
      quantity: 0, // 加购单位数量
      sum_quantity: parseFloat(0), // 基础单位数量
      aux_quantity: parseFloat(0), // 销售单位数量
    }
    for (var k = 0; k < rule.Products.length; k++) {
      var p = rule.Products[k];
      for (var l = 0; l < p.Goods.length; l++) {
        var g = p.Goods[l];
        //计算单个货品小计
        cart.caculateSubtotal(g);
        if (g.IsChecked) {
          var quantity = g.AuxQty || 0;
          // 计算总价
          rulePrice.price += util.keepDecimal("ceil", (g.sale_price || 0) * quantity, 2);
          rulePrice.integral += util.keepDecimal("ceil", (g.pay_integral || 0) * quantity, 0);
          rulePrice.originalPrice += util.keepDecimal("ceil", (g.sale_price || 0) * quantity,2);
          rulePrice.quantity += quantity;
          rulePrice.sum_quantity += util.keepDecimal("ceil", quantity * (g.AuxRate || 1), 4);
          rulePrice.aux_quantity += util.keepDecimal("ceil", quantity * (g.AuxRate || 1) / (g.DefaultUnitTranslated || 1), 4);
        }
      };
    };
    rulePrice = cart.calacPromotion(gPromotion, rulePrice);
    return rulePrice;
  },
  /**
   * 获取价格(数量在某个阶梯内显示的价格)
   * @param  {[type]} o [description]
   * @return {[type]}   [description]
   */
  getPrice: function(g) {
    var quantity = g.AuxQty || 0,
      price = g.SalesPrice,
      integral = g.SalesIntegral;
    // CanPartakePromotions：特价商品是否参与促销活动
    // 当参与促销活动时也需要计算参与后的价格
    if (g.DiscountId > 0 && (g.DiscountType == 2 && g.CanPartakePromotions != 1)) {
      price = g.SalesPrice;
    } else {
      var t = detail.parseRule(g.UnitPrices, g.AuxRate, quantity);
      if (t.has) {
        price = t.price;
        if (g.IsDeduction != 1) {
         integral = t.integral;
        }
      }
    }
    var gp = {
      price: parseFloat(price),
      integral: parseFloat(integral, 0)
    };
    return gp;
  },

  /**
   * 返回价格力显示信息 saleMode 销售模式; -- 0现金，1积分，2现金+积分
   * @param  {object} goods   当前货品
   * @param  {bool} sum 是否计算
   * @return {[string]}        返回重新处理后的价格显示
   */
  displayPrice: function(g, sum) {
    var gp = cart.getPrice(g);
    if (typeof(sum) == "boolean" && sum) {
      if (g.Stock < g.Quantity) g.Quantity = g.Stock;
      if (parseFloat(g.AuxRate) > 1) {
        gp.price = gp.price * (g.Quantity * g.AuxRate);
        gp.integral = gp.integral * (g.Quantity * g.AuxRate);
      } else {
        gp.price = gp.price * g.Quantity;
        gp.integral = gp.integral * g.Quantity;
      }
      gp.quantity = g.Quantity;
    }
    // 积分抵扣
    if (g.IsDeduction) {
      g.sale_price = gp.price;
    } else {
      // 销售模式处理
      if (g.SaleMode == 0) {
        g.sale_price = gp.price;
      } else if (g.SaleMode == 1) {
        g.pay_integral = gp.integral;
      } else {
        g.sale_price = gp.price;
        if (gp.integral > 0)
          g.pay_integral = gp.integral;
      }
    } 
  },
  /**
   * 价格规则
   * @param  {Array}  rules     价格规则
   * @param  {[type]}  saleMode   [description]
   * @param  {Boolean} isDeduction [description]
   * @param  {[type]}  deductRate  [description]
   * @return {[type]}             [description]
   */
  displayLadderPrice: function(g, deductRate, fkway,Currency) {
    var ladders = [];
    if (fkway == 2) { // 对批发业务进行处理
      if (g.UnitPrices) { //阶梯价
        var rules = g.UnitPrices[g.AuxRate];
        for (var i = 0; rules && i < rules.length && rules.length > 1; i++) {
          var r = rules[i],
            txt = {
              ladder: "",
              price: ""
            };
          // 处理数量
          if (r.MaxQuantity == 2147483647) {
            txt.ladder = "购>" + (r.MinQuantity - 1) + "" + g.AuxUnit + " ";
          } else {
            txt.ladder = "购>" + (r.MinQuantity - 1) + g.AuxUnit + " ";
          }
          var price = parseFloat(r.Price),integral = r.Integral;
          // 积分抵扣
          if (g.IsDeduction) {
            txt.price += Currency + price;
            if (integral > 0 && deductRate > 0) {
              var deMoney = parseFloat(integral * deductRate);
              txt.price += " 可抵" +Currency+ deMoney.toFixed(2);
            }
          } else {
            // 销售模式处理
            if (g.SaleMode == 0) {
              txt.price += Currency + price
            } else if (g.SaleMode == 1) {
              txt.price += integral + "积分"
            } else {
              txt.price += Currency + price + "+" + (integral > 0 ? integral + "积分" : "");
            }
          }
          ladders.push(txt);
        }
      } else { //体系价，因为只有一项，只显示可抵金额就可以了
        if (g.IsDeduction) {
          var txt = {
              ladder: "",
              price: ""
            },
            integral = parseFloat(g.DeductionIntegral, 0);
          if (integral > 0 && deductRate > 0) {
            var deMoney = parseFloat(integral * deductRate);
            txt.price = "积分可抵"+Currency + deMoney.toFixed(2);
          }
          ladders.push(txt);
        }
      }
    } else { // 针对零售进行价格说明
      if (g.IsDeduction) { // 积分抵扣 ，只对积分抵扣进行购物车展示
        var txt = {
            ladder: "",
            price: ""
          },
          price = parseFloat(g.SalesPrice),
          integral = parseFloat(g.DeductionIntegral, 0);

        if (integral > 0 && deductRate > 0) {
          var deMoney = parseFloat(integral * deductRate);
          txt.price = "可用" + integral + "积分抵"+Currency + deMoney.toFixed(2);
        }
        ladders.push(txt);
      }
    }
    g.ladders = ladders;
  },

  /**
   * [submitOrder 提交订单]
   * @param  {[type]}   source   [数据源]
   * @param {Object} giftInfo 用户选择的赠品信息
   */
  submitOrder: function(source, giftInfo = {}, callback) {
    // console.log(source,'=========1');
    source.map(function(seller, i) {
      seller.PromotRules.map(function(rule, j) {
        rule.Products.map(function(p, k) {
          p.Goods.map(function(g, l) {

            if (g.IsChecked) {
              if (cart.judge_quantity(g, g.Quantity, p.ZeroStockBuy)) {
                if (callback != undefined && typeof(callback) == "function") {
                  callback(source);  
                }
                return;
              }
            }
          });
        });
      });
    });
    console.log(source)
    var data = cart.decorateOrderData(source, giftInfo);
    if (data == "") {
      util.alert("请选择商品");
      return;
    }
    var base64 = util.base64_encode(data);
    // console.log(util.base64_decode(base64));
    router.navigate({
      path: "orderConfirm",
      params: {
        productinfo: base64
      }
    });
  },
  /**
   * [decorateOrderData 组装订单数据]
   * @param  {[type]}   source   [数据源]
   * @param {Object} giftInfo 用户选择的赠品信息
   */
  decorateOrderData: function(source, giftInfo) {
    var carts_arr = [];
    var gift = []
    source.map(function(seller, i) {
      seller.PromotRules.map(function(rule, j) {
        let Promotion = rule.Promotion || {}
        let isCompose = false // 是否为组合促销
        if (!isEmpty(Promotion)) {
          if (Promotion.PromotionType == 2) {
            isCompose = true
          }
        }
        rule.Products.map(function(p, k) {
          p.Goods.map(function(g, l) {
         
            if (g.IsChecked&&g.IsBuy==1) {
              carts_arr.push(`
            <Goods>
              <SupplierId>${seller.Id}</SupplierId>
              <PromotRuleId>${g.RuleId || 0}</PromotRuleId>
              <BuyTypeId>0</BuyTypeId>
              <BuyType>Cart</BuyType>
              <Id>${g.Id}</Id>
              <productid>${p.ProductId}</productid>
              <goodsid>${g.GoodsId}</goodsid>
              <specvalue><![CDATA[${g.SpecValue == "无" ? "" : (g.SpecValue)}]]></specvalue>
              <quantity>${g.Quantity * g.AuxRate}</quantity>
              <DiscountType>${g.DiscountType}</DiscountType>
              <DiscountId>${g.DiscountId}</DiscountId>
              <AuxRate>${g.AuxRate}</AuxRate>
              <AuxUnit><![CDATA[${(g.AuxUnit)}]]></AuxUnit>
              <AuxQty>${g.AuxQty}</AuxQty>
              <depotid>0</depotid>
              <Multiple>${rule.Multiple}</Multiple>
            </Goods>
            `);
              let key = ''
              if (isCompose) {
                key = `${seller.Id}_${rule.RuleId}_0`
              } else {
                key = `${g.Id}_${g.RuleId}_${g.GoodsId}`
              }
              if (!isEmpty(giftInfo[key])) {
                gift.push(giftInfo[key].selectedInfo)
              }
            }
          });
        });
      });
    });
    carts_arr = carts_arr.join("")
    if (gift.length > 0) {
      gift = gift.join('')
      gift = `
        <SelectedPromotGifts>${gift}</SelectedPromotGifts>
      `
      carts_arr += gift
    }
    return carts_arr
  },
  /**
   * 获取购物车数量
   */
  get_cart_count: (callback) => {
    var entity = authorize.getEntity();
    if (entity == undefined) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(0);
      } else {
        let tabbar = getTabbar()
        tabbar.setTabBarBadge(0)
        app.setTabBarBadge(0);
      }
      return;
    };
    var param = {
      FKId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity.fkId,
      proprietor: app.dns.proprietor,
      proprietorId: app.dns.proprietorId
    };
    util.post("order.cart.count", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res);
        } else {
          let tabbar = getTabbar()
          tabbar.setTabBarBadge(res.Content)
          app.setTabBarBadge(res.Content);
        }
      }
    }, "3.0", null, false);
  },
  /**批量加入购物车*/
  batchAddCart(goodsXml,callback) {
    var entity = authorize.getEntity();
    var parmas = {
      Token: entity && entity.manager ? entity.manager.Token : '',
      Product: goodsXml,
      loginedId: entity ? entity.fkId : 0,
      ProprietorId: app.dns.proprietorId
    };
    cart.addGoodsCart(parmas,function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Success, res.Content);
      }
    }, "3.0");
  },
  /**加入购物车 */
  /**cinfo=
   * <Carts>
   *      <Cart>
   *        <ProductId>pid</ProductId>
   *        <GoodsId>gid</GoodsId>
   *        <SpecValue>spv</SpecValue>
   *        <Quantity>num </Quantity>
   *      </Cart>
   * </Carts>
   * Append=1表示增加数量 0为改变数量*/
  addGoodsCart(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      Token: entity && entity.manager ? entity.manager.Token : '',
      UserId: entity ? entity.fkId : 0,
      Product: data.Product
    };

    util.post("order.speed.join", param, function(res) {
      res = res.data;
      if (res.Success == true) {
        //操作成功
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
        //更新购物车数量 
        cart.get_cart_count();
      } else {
        util.alert("操作失败:" + res.Message);
      }
    }, "3.0", null, false);
  },
  // 向购物车添加套装
  packedAddCart(data,callback){
    var entity = authorize.getEntity();
    var param = {
      Token: entity && entity.manager ? entity.manager.Token : '',
      Multiple:data.num,
      GoodsIds:data.GoodsIds,
      PackedId:data.PackedId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor
    };
    util.post("order.cart.packed.add", param, function(res) {
      res = res.data;
      if (res.Success == true) {
        //操作成功
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      } else {
        util.alert("操作失败:" + res.Message);
      }
    }, "3.0", null, false);
  },
  // 购物车，套装选中状态通知接口
  packedChecked(data,callback){
    var entity = authorize.getEntity();
    var param = {PackedId:data.PackedId,status:data.status,Token:entity && entity.manager ? entity.manager.Token : '',UserId:entity != undefined ? entity.fkId : 0, ProprietorId: app.dns.proprietorId}
    util.post("order.cart.packed.checked", param, function(res) {
      res = res.data;
      if (res.Success == true) {
        //操作成功
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      } else {
        util.alert("操作失败:" + res.Message);
      }
    }, "3.0", null, false);
  },
  // 购物车，套装数量修改通知接口
  packedChange(data,callback){
    var entity = authorize.getEntity();
    var param = {PackedId:data.PackedId,AreaId:data.AreaId,Multiple:data.Multiple,Token:entity && entity.manager ? entity.manager.Token : '',UserId:entity != undefined ? entity.fkId : 0, ProprietorId: app.dns.proprietorId};
    util.post("order.cart.packed.change", param, function(res) {
      res = res.data;
      if (res.Success == true) {
        //操作成功
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      } else {
        util.alert("操作失败:" + res.Message);
      }
    }, "3.0", null, false);
  },
  // 删除购物车中指定套装
  packedDelete: function(source, goodsIds,CartName, callback) {
    var entity = authorize.getEntity();
    var param = {PackedId:goodsIds,Token:entity && entity.manager ? entity.manager.Token : '',UserId:entity != undefined ? entity.fkId : 0, ProprietorId: app.dns.proprietorId};
    util.confirm(function() {
      util.post("order.cart.packed.delete", param, function(res) {
        res = res.data;
        if (res.Success == true) {
          //操作成功
            util.success("删除成功", function() {
              //回调
              if (callback != undefined && typeof(callback) == "function") {
                callback(source);
                //更新购物车数量
                cart.get_cart_count(CartName);
              }
            });
        }else{
          util.alert("操作失败:" + res.Message);
        }
      }, "3.0", null, false);
    }, null, "是否确认删除购物车商品", "确认删除")
  },
  /**
   * 优惠信息按满的数量排序
   * 
   * @param {Object} promotions
   */
  promotionsSorting (promotions = {}) {
    if (isEmpty(promotions)) {
      return promotions
    }
    for (let i in promotions) {
      let item = promotions[i] || []
      if (Array.isArray(item)) {
        for (let j in item) {
          let PromotLadder = item[j].PromotLadder || []
          PromotLadder.sort((a, b) => {
            return a.MinimumValue - b.MinimumValue
          })
          item[j].PromotLadder = PromotLadder
        }
      }
      promotions[i] = item
    }
    return promotions
  },
}


/**订单费用相关 */
const fee = {
  /**计算运费 */
  calFreight(data, callback) {
    var entity = authorize.getEntity();
    // console.log(data,'----data');
    // if (data.FreightMode == 1 && data.FreeFreight == false) {
      var param = {
        Token:entity && entity.manager ? entity.manager.Token : '',
        FKFlag: app.dns.proprietor,
        FKId: app.dns.proprietor,//data.SettleType == 1 ? 0 : data.SupplierId
        ProprietorId: app.dns.proprietorId,
        Proprietor: app.dns.proprietor,
        Weight: data.Weight || 0,
        AddressId: data.AddressId || 0,
        FeeMode:data.FreightMode || '',
        TotalAmount:data.Price || 0,
        deliveryId:data.DeliveryId || 0,//送货时间
        BuyCount:data.BuyCount || 0,//
        FreightAmount:data.FreightAmount,
        Flag:data.flag || 0
      };
      util.post("order.freight.get", param, function(res) {
        res = res.data;
        var freight = parseFloat(res.Content);
        freight = freight == undefined || isNaN(freight) ? 0 : freight;
        if (callback != undefined && typeof(callback) == "function") {
          callback(freight);
        }
      }, "3.0", null, false);
    // }
  },
  /**
   * 积分抵扣运费
   * @param {String | Number} Freight 运费
   */
  integralReduceFreight(Freight) {
    return new Promise((resolve, reject) => {
      let entity = authorize.getEntity() || {}
      let manager = entity.manager || {}
      let param = {
        Token: manager.Token || '',
        FKFlag: app.dns.proprietor,
        FKId: app.dns.proprietor, //data.SettleType == 1 ? 0 : data.SupplierId
        ProprietorId: app.dns.proprietorId,
        Proprietor: app.dns.proprietor,
        Freight: Freight || '', // 运费
        BuyerId: entity.fkId, // 当前登录人
      }
      util.post("order.freight.getdeductionconfig", param, function (res) {
        res = res.data || {}
        if (res.Success) {
          resolve(res)
        } else {
          console.log('使用积分抵扣运费失败', res)
          reject(res)
        }
      }, "3.0", null, false)
    })
  },
  /**1.加载税率等配置项
   * 2.读取当前商家是否需要开发票
   * 3.获取上一次下单选择的发票信息
   * @param data包含当前税率 普票和增值票的税率
   * */
  initInvoiceInfo(callback) {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      (model) => {
        var invoiceRate = {
          PTInvoiceRate: model.PTInvoiceRate,
          ZZInvoiceRate: model.ZZInvoiceRate,
          FreightMode: model.FreightMode,
          IsInvoice: false
        }
        that.loadIsInvoice(invoiceRate, callback);
      });
  },
  /**是否开发票 */
  loadIsInvoice(invoiceRate, callback) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      Token: entity && entity.manager ? entity.manager.Token : '',
      ProprietorId: app.dns.proprietorId
    };
    util.post("store.storerelate.isinvice", param, function(res) {
      res = res.data;
      var isInvoice = false;
      if (res.Success) {
        isInvoice = res.Content;
      }
      invoiceRate.IsInvoice = isInvoice;
      that.findDefaultInvo(invoiceRate, callback);
    }, "3.0", null, false);
  },
  /**获取上一次下单选择的发票信息 */
  findDefaultInvo(invoiceRate, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      StoreId: entity ? entity.fkId : 0,
      Token: entity && entity.manager ? entity.manager.Token : '',
      proprietorId: app.dns.proprietorId,
      proprietor: app.dns.proprietor,
    };
    util.post("order.invoice.info", param, function(res) {
      res = res.data;
      if (res.Success) {
        res = res.Content[0];
        var InvType = res.InvType;
        var invoMsg = "您已经选择不开具发票！";
        var nowInvoiceRate = invoiceRate.NowInvoiceRate;
        var invoice = "<Invoice><InvType>0</InvType></Invoice>";
        var taxpayerType = res.TaxpayerType;
        if (invoiceRate.IsInvoice == 0) {
          InvType = 0;
        }
        if (InvType == 1) {
          nowInvoiceRate = invoiceRate.PTInvoiceRate;
          invoMsg = "您已经选择开普通发票！";
          var data = "<Invoice>";
          data += '<InvType>1</InvType>';
          data += '<TaxpayerType>' + res.TaxpayerType + '</TaxpayerType>';
          data += '<InvTitle>' + res.InvTitle + '</InvTitle>';
          data += '<Code>' + (res.Code||"") + '</Code>';
          data += '<Content>' + res.Content + '</Content>';
          data += "</Invoice>";
          invoice = data.toString();
        } else if (InvType == 2) {
          taxpayerType = 0;
          nowInvoiceRate = invoiceRate.ZZInvoiceRate;
          invoMsg = "您已经选择开增值税发票！";
          var data = "<Invoice>";
          data += '<InvType>2</InvType>';
          data += '<Name>' + res.Name + '</Name>';
          data += '<Code>' + res.Code + '</Code>';
          data += '<Address>' + res.Address + '</Address>';
          data += '<Tel>' + res.Tel + '</Tel>';
          data += '<Bank>' + res.Bank + '</Bank>';
          data += '<Account>' + res.Account + '</Account>';
          data += '<PostAddress><![CDATA[' + res.PostAddress + ']]></PostAddress>';
          data += "</Invoice>";
          invoice = data.toString();
        }
        var invoiceInfo = {
          TaxpayerType: taxpayerType == null ? 0 : taxpayerType,
          InvPTTitle: res.InvTitle,
          InvoPTCode: res.Code||"",
          InvoPTContent: res.Content == null ? "明细" : res.Content,
          InvoZZName: res.Name,
          InvoZZCode: res.Code,
          InvoZZAddress: res.Address,
          InvoZZTel: res.Tel,
          InvoZZBank: res.Bank,
          InvoZZAccount: res.Account,
          InvoZZPostAddress: res.PostAddress
        };
        var resultData = {
          InvoiceId: res.Id,
          invoiceRate: invoiceRate,
          InvoiceType: InvType,
          invoiceMsg: invoMsg,
          invoice: invoice,
          invoiceInfo: invoiceInfo
        };
        if (callback != undefined && typeof(callback) == "function") {
          callback(resultData);
        }
      } else {
        if (callback != undefined && typeof(callback) == "function") {
          callback(null);
        }
      }
    }, "3.0");
  },
  /**计算税费*/
  calInvRate(data) {
    var amount = parseFloat(data.ProductAmount) - parseFloat(data.CouponDiscount) - parseFloat(data.DeductionTotal);
    var invoiceRate = parseFloat(data.NowInvoiceRate);
    var taxes = amount * (invoiceRate / 100);
    return taxes;
  },
  /**保存普通发票 */
  savePTInvo(data) {
    var invoStr = "<Invoice>";
    invoStr += '<InvType>1</InvType>';
    invoStr += '<TaxpayerType>' + data.TaxpayerType + '</TaxpayerType>';
    invoStr += '<InvTitle>' + data.InvPTTitle + '</InvTitle>';
    if (data.TaxpayerType == 1) {
      invoStr += '<Code>' + data.InvoPTCode + '</Code>';
    }
    invoStr += '<Content>' + data.InvoPTContent + '</Content>';
    invoStr += "</Invoice>";
    return invoStr.toString();
  },
  /**保存增值税发票 */
  saveZZInvo(data) {
    var invoStr = "<Invoice>";
    invoStr += '<InvType>2</InvType>';
    invoStr += '<Name>' + data.InvoZZName + '</Name>';
    invoStr += '<Code>' + data.InvoZZCode + '</Code>';
    invoStr += '<Address>' + data.InvoZZAddress + '</Address>';
    invoStr += '<Tel>' + data.InvoZZTel + '</Tel>';
    invoStr += '<Bank>' + data.InvoZZBank + '</Bank>';
    invoStr += '<Account>' + data.InvoZZAccount + '</Account>';
    invoStr += '<PostAddress>' + data.InvoZZPostAddress + '</PostAddress>';
    invoStr += "</Invoice>";
    return invoStr;
  },
  /**重新计算订单实付款价格 */
  /**
   * isCalcFreight：是否用于计算运费
   */
  calPayables(datas,isContain=true,isCalcFreight=false) {
    //商品金额
    var productAmount = parseFloat(datas.ProductAmount) == undefined ? 0 : parseFloat(datas.ProductAmount);
    //运费
    var freight = parseFloat(datas.Freight) == undefined ? 0 : parseFloat(datas.Freight);
    //税费
    var taxes = parseFloat(datas.Taxes) == undefined ? 0 : parseFloat(datas.Taxes);
    //优惠劵优惠
    var couponDiscount = parseFloat(datas.CouponDiscount) == undefined ? 0 : parseFloat(datas.CouponDiscount);
    //支付优惠
    var payDiscount = parseFloat(datas.PayDiscount) == undefined ? 0 : parseFloat(datas.PayDiscount);
    //积分抵现
    var deductionTotal = parseFloat(datas.DeductionTotal) == undefined || datas.useGrade ? 0 : parseFloat(datas.DeductionTotal);
    //购物车优惠
    var discountAmount = parseFloat(datas.DiscountAmount) == undefined ? 0 : parseFloat(datas.DiscountAmount);
    var totalAmount = productAmount + (isCalcFreight ? 0 : (freight + taxes));
    var discounts = discountAmount + couponDiscount + payDiscount + (isContain?deductionTotal:0);
    var payables = parseFloat(totalAmount) - parseFloat(discounts);
    return payables;
  },
  /**订单确认使用积分抵扣*/
  calDeductionTotal(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      DeductionIntegral: data.inputIntegral,
      Token:entity && entity.manager ? entity.manager.Token : '',
      Amount:data.Amount
    }
    console.log(data.Amount,'========1');
    util.post("order.trade.deductionintegral", param, function(res) {
      res = res.data;
      var deductionTotal = 0;
      if (res.Success && res.Content.Result == 1) {
        if (parseFloat(data.payables) >= parseFloat(res.Content.DeductionTotal)) {
          deductionTotal = res.Content.DeductionTotal;
        } else {
          util.tips("积分抵扣金额大于订单金额(不含运费)，最多允许抵扣：" + data.payables + "元");
        }
      } else {
        util.alert(res.Content.Error || res.Message);
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(deductionTotal);
      }
    }, "3.1", null, false);
  }
}
/**
 * 订单列表
 */
const orderlist = {
  /**
   * 加载订单列表
   */
  loadList(index, data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FromFKFlag: entity ? entity.fkFlag : 1,
      FromFKId: entity ? entity.fkId : 0,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      SearchKeyword: data.keywords,
      sortField: data.sortField,
      sortDirect: data.sortDirect,
      consigneeKeyword:data.consigneeKeyword || '',
      consigneeAddress:data.consigneeAddress || '',
      ProductKeyword:data.ProductKeyword || '',
      proprietor:app.dns.proprietor,
      Status: index,
      StartDeliveryTime: data.StartDeliveryTime || '',
      EndDeliveryTime: data.EndDeliveryTime || ''
    };
    if (param.Status == 70) {
      param.Status = 7;
      param.IsComment = 0;
    }else if(param.Status == 60){
      param.Status = 6;
      param.IsComment = 0;
    }
    var val = Object.assign(param,data.orderData?data.orderData:{})
    // return;
    util.post("order.order.listbybuyers", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          var content = res.Content;
          for (var i = 0; i < content.data.length; i++) {
            orderlist.getPayName(content.data[i]);
            // console.log(content.data[i]);
          }
          callback(content, entity.fkId);
        }
      } else {
        util.alert(res.Message);
      }
    }, "2.0");
  },
  offlineData(index, data, callback){
    var entity = authorize.getEntity();
    var param = {
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      StoreId:entity.fkId,
      KeyWord:data.keywords,
      FKId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
    };
    util.post("supplier.erp.salesorder", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          var content = res.Content;
          for (var i = 0; i < content.data.length; i++) {
            content.data[i].ItemsQty = Number(content.data[i].ItemsQty);
            orderlist.getPayName(content.data[i]);
            var items = content.data[i].OrderItems;
            for(var j=0;j<items.length;j++){
              items[j].Qty = Number(items[j].Qty);
            }
            // console.log(content.data[i]);
          }
          callback(content, entity.fkId);
        }
      } else {
        util.alert(res.Message);
      }
    }, "3.1");
  },
  /**
   * 获取erp订单退换货详情
   */
  getOfflineRetreatinfo(data) {
    let entity = authorize.getEntity() || {}
    let param = {
      KeyWord: data.keywords, // 订单号
      PageIndex: data.PageIndex || 1,
      PageSize: data.PageSize || 20,
      StoreId: entity.fkId,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
    }
    return new Promise((resolve, reject) => {
      util.post("supplier.erp.retreat", param, function (res) {
        res = res.data
        if (res.Success) {
          var content = res.Content
          for (var i = 0; i < content.data.length; i++) {
            content.data[i].ItemsQty = Number(content.data[i].ItemsQty)
            orderlist.getPayName(content.data[i])
            var items = content.data[i].OrderItems
            for (var j = 0; j < items.length; j++) {
              items[j].Qty = Number(items[j].Qty)
            }
          }
          resolve(content)
        } else {
          util.alert(res.Message)
          reject(res)
        }
      }, "3.1");
    })
  },
  /**
   * 获得支付名称
   */
  getPayName: function(o) {
    if (o.PayName) {
      o.PayName = o.PayName;
    } else if (o.PayTypeId == 1) {
      o.PayName = "货到付款";
    } else if (o.PayTypeId == 2) {
      o.PayName = "在线支付";
    } else if (o.PayTypeId == 3) {
      o.PayName = "授信支付";
    } else if (o.PayTypeId == 4) {
      o.PayName = "转账汇款";
    } else if (o.PayTypeId == 5) {
      o.PayName = "线下付款";
    }
  },

  /**
   * 取消订单
   */
  cancelOrder: function(data, callback,navigateCallback) {
    var entity = authorize.getEntity();
    data.FKId = entity ? entity.fkId : 0;
    data.FKFlag = entity ? entity.fkFlag : 1;
    data.proprietor = app.dns.proprietor;
    data.proprietorId = app.dns.proprietorId;
    util.post("order.trade.cancel", data, function(res) {
      res = res.data;
      if (res.Success) {
        if (res.Content > 0) {
          util.tips('取消订单成功')
      } else if (res.Content == -1) {
        util.tips('没有取消订单的操作权限')
      } else if (res.Content == -2) {
        util.tips('当前状态不能取消')
      } else if (res.Content == -11) {
        if (navigateCallback != undefined && typeof(navigateCallback) == "function") {
          navigateCallback();
        }
        router.navigate({
          path: "financeAccountList"
        });
        return;
      } else {
        util.tips('取消失败')
      }
        if (callback != undefined && typeof(callback) == "function") {
          callback();
        }
      } else {
        alert({
          content: res.Message || "订单取消失败"
        })
        if (type.isFunction(navigateCallback)) {
          navigateCallback()
        }
      }

    }, "3.1", null, false);
  },
  /**
   * 删除订单
   */
  deleteOrder:function(orderId,callback){
    util.confirm(function() {
      var entity = authorize.getEntity();
      var param = {
        OrderId:orderId,
        FKId: entity ? entity.fkId : 0,
        FKFlag: entity ? entity.fkFlag : 0,
        Token: entity && entity.manager ? entity.manager.Token : '',
        proprietor : app.dns.proprietor,
        proprietorId : app.dns.proprietorId
      }
      util.post("order.trade.logicaldelorder", param, function(res) {
        res = res.data;
        if(res.Content > 0){
          util.tips("删除成功")
          if (callback != undefined && typeof(callback) == "function") {
            callback();
          }
        }else{
          util.tips(res.Message)
        }
      }, "3.0", null, false);
    }, function() {}, "是否确认删除此订单?", "确认删除");
  },
  /**
   * 立即支付
   */
  onPay: function(orderId, callback) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      token: entity && entity.manager ? entity.manager.Token : '',
      clerkToken: "0|" + this.generateTimeReqestNumber(),
      OrderId: orderId,
      FKId: entity ? entity.fkId : 0,
      FKFlag: entity ? entity.fkFlag : 0,
      proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId
    };
    if (entity == undefined || entity.fkId == 0) {
      param.other = 1;
    }
    util.post("order.trade.immediatelypay", param, function(res) {
      res = res.data;
      if (res.Success && parseInt(res.Content.Result) == 1) {
        orderPay.findPayOrderData(res.Content.Data, "cashier");
      } else {
        util.tips("订单支付失败");
        // 调取订单支付失败，则刷新页面
        if (res.code == 1510) {
          callback(res)
        }
      }
    }, "3.0", null, false);
  },
  /**
   * 合并支付
   */
  mergePay: function(orderids, payTypeId) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      token: entity && entity.manager ? entity.manager.Token : '',
      clerkToken: "0|" + this.generateTimeReqestNumber(),
      OrderIds: orderids,
      PayTypeId: payTypeId,
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.trade.mergepay", param, function(res) {
      res = res.data;
      if (res.Success && parseInt(res.Content.Result) == 1) {
        orderPay.findPayOrderData(res.Content.Data, "cashier");
      } else {
        util.alert("订单支付失败");
      }

    }, "3.0", null, false);
  },
  /**
   * 确认收货
   */
  confirmReceive: function(oddnumber, callback) {
    var that = this;
    var entity = authorize.getEntity();
    util.confirm(function() {
      var param = {
        fkid: entity ? entity.fkId : 0,
        OddNumber: oddnumber,
        Token: entity && entity.manager ? entity.manager.Token : '',
        RoleType: "store",
        proprietor: app.dns.proprietor,
        ProprietorId: app.dns.proprietorId
      };
      util.post("order.trade.chkreceivingnew", param,
        function(res) {
          res = res.data;
          if (res.Success) {
            var content = parseInt(res.Content);
            if (content > 0) {
              if (res.Message.length > 0 && res.Message.includes('奖励积分')) {
                util.alert("确认收货成功，" + res.Message)
              } else {
                util.alert("确认收货成功")
              }
              if (callback != undefined && typeof(callback) == "function") {
                callback();
              }
            } else if (content == -12) {
              util.alert("部分收货情况，请检查是否有发货信息:");
              return;
            }
          } else {
            util.tips("确认收货失败:" + res.Message);
            return;
          }
        }, "3.0");
    }, null, "是否确认收货", "确认收货")
  },
  /**
   * 直接收货 (微信确认收货组件成功后调用)
   * @param {*} oddnumber 
   * @param {*} callback 
   */
  receiveNow: function (oddnumber, callback) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      fkid: entity ? entity.fkId : 0,
      OddNumber: oddnumber,
      Token: entity && entity.manager ? entity.manager.Token : '',
      RoleType: "store",
      proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.trade.chkreceivingnew", param,
      function (res) {
        res = res.data;
        if (res.Success) {
          var content = parseInt(res.Content);
          if (content > 0) {
            if (res.Message.length > 0 && res.Message.includes('奖励积分')) {
              util.alert("确认收货成功，" + res.Message)
            } else {
              util.alert("确认收货成功")
            }
            if (callback != undefined && typeof (callback) == "function") {
              callback();
            }
          } else if (content == -12) {
            util.alert("部分收货情况，请检查是否有发货信息:");
            return;
          }
        } else {
          util.tips("确认收货失败:" + res.Message);
          return;
        }
      }, "3.0");
  },
  /**
   * 
   */
  pad2: function(n) {
    return n < 10 ? '0' + n : n
  },
  /**
   * 产生随机请求数
   */
  generateTimeReqestNumber: function() {
    var date = new Date();
    return date.getFullYear().toString() +
      this.pad2(date.getMonth() + 1) +
      this.pad2(date.getDate()) +
      this.pad2(date.getHours()) +
      this.pad2(date.getMinutes()) +
      this.pad2(date.getSeconds());
  },
  /**
   * 加载欠款订单列表
   */
  load_arrears_list: (page, callback) => {
    var entity = authorize.getEntity();
    var param = util.mergeJsonObject(page, {
      token: entity && entity.manager ? entity.manager.Token : '',
      FKId: entity ? entity.fkId : 0,
      FKFlag: entity ? entity.fkFlag : 1,
      ProprietorId: app.dns.proprietorId
    });
    util.post("order.arrears.page", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.alert(res.Content);
      }
    });
  },
  /**
   * 货到付款，已经完成，但未付款的
   */
  repay_order: (orderids) => {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      token: entity && entity.manager ? entity.manager.Token : '',
      OrderIds: orderids,
      FKId: entity ? entity.fkId : 0,
      FKFlag: entity ? entity.fkFlag : 1,
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.arrears.repay", param, function(res) {
      var res = res.data;
      if (!res.Success) {
        util.alert(res.Message);
        return;
      } else {
        var o = res.Content;
        orderPay.findPayOrderData(o, "cashier");
      }

    });
  }
}
/**
 * 订单详情
 */
const orderdetail = {
  /**
   * 获得订单详情
   */
  getDetail: function(oddNumber,view,callback) {
    var entity = authorize.getEntity();
    var param = {
      OddNumber: util.base64_encode(oddNumber),
      IsBuyer: 1,
      FromFKFlag: entity ? entity.fkFlag : 1,
      FromFKId:  entity ? entity.fkId : 0,
      Token: entity && entity.manager ? entity.manager.Token : '',
      view: view
    };

    util.post("order.trade.getorderinfo", param,
      function(res) {
        res = res.data;
        if (!res.Success) {
          util.alert("您没有权限查看此订单信息！");
          //跳转到订单列表
          router.redirect({
            path: "orderList"
          });
        } else {
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content[0]);
          }
        }
      }, "3.0");
  },
  /**
   * 
   */
  getDispatchInfo: function(orderId, callback) {
    var entity = authorize.getEntity();
    var param = {
      OrderId: orderId,
      FKId: entity ? entity.fkId : 0
    };

    util.post("order.trade.dispatchinfo", param,
      function(res) {
        res = res.data;
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }, "3.0");
  },
  /**
   * 获得发票信息
   */
  getInvoiceInfo: function(orderId, callback) {
    var entity = authorize.getEntity();
    var param = {
      OrderId: orderId,
      FKId: entity ? entity.fkId : 0
    };

    util.post("order.trade.invoiceinfo", param,
      function(res) {
        res = res.data;
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }, "3.0");
  },
  /**
   * 返修退换
   */
  getRetreatinfo: function(orderId, callback) {
    var entity = authorize.getEntity();
    var param = {
      OrderId: orderId,
      FromFKId: entity ? entity.fkId : 0,
      Token: entity && entity.manager ? entity.manager.Token : '',
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
    };
    util.post("order.trade.retreatinfo", param,
      function(res) {
        res = res.data;
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }, "3.0");
  },
  /**
   * 获取订单最后一个发货物流信息接口
   * @param {String} DispatchNumber 物流单号
   */
  getLogistics:function(orderId, DispatchNumber, callback){
    var entity = authorize.getEntity();
    var param = {
      OrderId: orderId,
      Token: entity && entity.manager ? entity.manager.Token : '',
      DispatchNumber: DispatchNumber
    };
    util.post("order.logistics.get",param,function(res){
      res = res.data;
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    },"3.1")
  },
  /**
   * 获得支付结束时间
   */
  getPayEndTime: function(orderId, callback) {
    var param = {
      OrderId: orderId,
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.trade.getpayendtime", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          if (callback != undefined && typeof(callback) == "function") {
            let content = res.Content.replace(/-/g, '/');
            callback(content);
          }
        }
      });
  },
  /**
   * 上传凭证
   */
  upload_voucher: (orderId, src, callback) => {
    var entity = authorize.getEntity();
    var param = {
      OrderId: orderId,
      Credentials: src,
      ProprietorId: app.dns.proprietorId,
      Token: entity && entity.manager ? entity.manager.Token : '',
    };
    util.post("order.trade.savecred", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          util.alert("上传凭证成功")
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert(res.Message);
        }
      }, null, false);
  },
  /**
   * 上传附件
   */
  upload_adjunct: (orderId, src, callback) => {
    var entity = authorize.getEntity();
    var param = {
      orderId: orderId,
      pics: src,
      ProprietorId: app.dns.proprietorId,
      Token: entity && entity.manager ? entity.manager.Token : '',
    };
    util.post("order.attachment.save", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          // util.tips("上传附件成功")
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert(res.Message);
        }
      },"3.1", null, false);
  },
  /**
   * 上传签收凭证
   */
  upload_sign: (orderId, src, callback) => {
    var entity = authorize.getEntity();
    var param = {
      orderId: orderId,
      imageUrl: src,
      ProprietorId: app.dns.proprietorId,
      Token: entity && entity.manager ? entity.manager.Token : ''
    };
    util.post("order.sign.picture", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          // util.alert("上传成功")
          wx.showToast({title: '上传成功',icon: 'success'});
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert(res.Message);
        }
      }, "3.0", null, false);
  },
  /**
   * 获得支付类型
   */
  getPaymentType(callback) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      Token: entity && entity.manager ? entity.manager.Token : '',
      FKWay: app.dns.fkWay,
      UserId: entity ? entity.fkId : 0,
      Terminal: 2
    };

    util.post("payment.paytype.list", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }

    }, "3.0");
  },
  /**
   * 提交 
   * */
  submitOrder: function(data, callback) {
    var entity = authorize.getEntity();
    var param = util.mergeJsonObject(data, {
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      ManagerId: entity && entity.manager ? entity.manager.ManagerId : 0,
      StoreId: entity ? entity.fkId : 0,
      Token: entity && entity.manager ? entity.manager.Token : '',
      ClerkId: entity == undefined || entity.fkFlag == 1 ? 0 : entity.fkId
    })
    util.post("order.trade.submitorder", param, function(res) {
      if (res.data.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.data.Content);
        }
      } else {
        util.alert(res.data.Message);
      }
    }, "3.0", null, false);
  }
}

/**
 * 拼团订单
 */
const grouporder = {
  /**拼团预售的立即购买,返回base64的加密字符串 */
  buyNowToGroup(flag, groupType, goodslist, goodsMode, quantityDigits) {
    var ary = [];
    var goodsIdArys = []; //购买的货品ids 
    var totalQuantity = 0;
    for (var i = 0; i < goodslist.length; i++) {
      var buyGood = goodslist[i];
      if (buyGood.ProductId != goodsMode.ProductId) continue;
      var num = isNaN(buyGood.CartCount) ? 0 : buyGood.CartCount; //当前个数
      if (num > 0) {
        //单位换算比例 
        var translated = buyGood.Translated;
        translated = (isNaN(translated) || translated == undefined) ? 1 : translated;
        ary.push("<Good><SupplierId>" + goodsMode.FKId + "</SupplierId>");
        ary.push("<FlagId>2</FlagId>");
        ary.push("<GroupId>" + goodsMode.Id + "</GroupId>");
        ary.push("<ProductId>" + goodsMode.ProductId + "</ProductId>");
        ary.push("<GoodsId>" + buyGood.Id + "</GoodsId>");
        ary.push("<Quantity>" + util.keepDecimal("ceil",(num * translated),quantityDigits) + "</Quantity>");
        ary.push("<Price>" + buyGood.SalesPrice + "</Price>");
        ary.push("<AuxUnit>" + buyGood.DefaultUnit + "</AuxUnit>");
        ary.push("<AuxRate>" + translated + "</AuxRate>");
        ary.push("<AuxQty>" + num + "</AuxQty>");
        ary.push("</Good>");
        totalQuantity += (num * translated);
        goodsIdArys.push(buyGood.Id);
      }
    }
    if (ary.length <= 0) {
      return "";
    }
    var dataAry = [];
    dataAry.push("<GroupId>" + goodsMode.Id + "</GroupId>");
    dataAry.push("<GoodsIds>" + goodsIdArys.join(',') + "</GoodsIds>");
    dataAry.push("<SupplierId>" + goodsMode.FKId + "</SupplierId>");
    dataAry.push("<GroupType>" + groupType + "</GroupType>");
    dataAry.push("<Flag>" + flag + "</Flag>");
    dataAry.push("<TotalQuantity>" + totalQuantity + "</TotalQuantity>");
    dataAry.push("<Goods>" + ary.toString() + "</Goods>");
    if (flag == 1 && groupType == 2) {
      dataAry.push("<GroupItemId>" + goodsMode.GroupItemId + "</GroupItemId>");
    }
    var productinfo = "<root>" + dataAry.join('') + "</root>";
    return util.base64_encode(productinfo);
  },
  /**检测拼团预售商品是否允许购买*/
  groupCanbuy(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      FKWay: app.dns.fkWay,
      BuyerFKId: entity.fkId,
      SellerFKId: data.SellerFKId,
      GroupId: data.GroupId,
      GoodsInfo: data.GoodsInfo,
    };
    util.post("market.groupbuy.canbuy", param, function(res) {
      if (res.data.Content == "") {
        if (callback != undefined && typeof(callback) == "function") {
          callback();
        }
      } else if (res.data.Content != undefined) {
        util.alert(res.data.Content);
      } else {
        util.alert(res.data.Message);
      }
    }, "3.0");
  },
  /**初始化订单确认页面的数据*/
  initGroupOrderConfirmData(pdata, callback) {
    var productInfo = util.base64_decode(pdata).replace(/\0/g, "");
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      UserId: entity.fkId,
      FKWay: app.dns.fkWay,
      ProductInfo: productInfo
    };
    util.post("order.groupbuy.getorderinfo", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(true, res.Content);
        }
      } else {
        if (callback != undefined && typeof(callback) == "function") {
          callback(false, res.Message);
        }
      }
    }, "3.0");
  },
  /**重新计算订单实付款价格 */
  /**
   * isCalcFreight：是否用于计算运费
   */
  calGroupPayables(data,isCalcFreight=false) {
    var productAmount = parseFloat(data.ProductAmount) == undefined ? 0 : parseFloat(data.ProductAmount);
    var freight = parseFloat(data.Freight) == undefined ? 0 : parseFloat(data.Freight);
    var taxes = parseFloat(data.Taxes) == undefined ? 0 : parseFloat(data.Taxes);
    var totalEarnest = parseFloat(data.TotalEarnest) == undefined ? 0 : parseFloat(data.TotalEarnest);
    var payables = productAmount + (isCalcFreight ? 0 : (freight + taxes));
    var resultFee = {
      payables: payables,
      retainage: (payables - totalEarnest)
    }
    return resultFee;
  },
  packOrderInfo(data) {
    var xmlAary = "<root>";
    //数据拼装 
    xmlAary += "<Flag>" + data.Flag + "</Flag>";
    xmlAary += "<GroupId>" + data.GroupId + "</GroupId>";
    xmlAary += "<GroupItemId>" + data.GroupItemId + "</GroupItemId>";
    xmlAary += "<ProductId>" + data.ProductId + "</ProductId>";
    var earnest = parseFloat(data.Earnest);
    if (earnest == undefined || earnest <= 0) {
      earnest = parseFloat(data.TotalOrderAmount);
    }
    xmlAary +="<IsDelivery>"+ data.IsDelivery +"</IsDelivery>";
    xmlAary += "<PickPointId>"+data.PickPointId+"</PickPointId>";
    xmlAary += `<LogisticsMode>${data.LogisticsMode}</LogisticsMode>`
    xmlAary += "<Earnest>" + earnest + "</Earnest>";
    xmlAary += "<AddressId>" + (data.consignee.AddressId || 0) + "</AddressId>";
    xmlAary += "<AddressIds>" + (data.consignee.AddressId || 0) + "</AddressIds>";
    xmlAary += "<AddressProvince>" + data.consignee.Province + "</AddressProvince>";
    xmlAary += "<PayTypeId>" + data.PayTypeId + "</PayTypeId>";
    xmlAary += "<PaymentId>" + data.PaymentId + "</PaymentId>";
    xmlAary += "<InvoiceId>" + data.InvoiceId + "</InvoiceId>";
    xmlAary += "<InvoiceType>" + data.InvoiceType + "</InvoiceType>";
    xmlAary += "<DeliveryId>0</DeliveryId>";
    xmlAary += "<DeliveryName>0</DeliveryName>";
    xmlAary += "<LogisticsCost>0</LogisticsCost>";
    xmlAary += "<Weight>" + data.TotalWeight + "</Weight>";
    xmlAary += "<SellerFKId>" + data.supplier.SupplierId + "</SellerFKId>";
    xmlAary += "<SupplierId>" + data.supplier.SupplierId + "</SupplierId>";
    xmlAary += "<SettleType>" + data.supplier.SettleType + "</SettleType>";
    xmlAary += "<FreeFreight>" + data.FreeFreight + "</FreeFreight>";
    xmlAary += "<Freight>" + data.Freight + "</Freight>";
    xmlAary += "<Taxes>" + data.Taxes + "</Taxes>";
    xmlAary += "<ProductAmount>" + data.TotalAmount + "</ProductAmount>";
    xmlAary += "<Payables>" + data.TotalOrderAmount + "</Payables>";
    xmlAary += "<Remark><![CDATA[" + data.BuyRemark + "]]></Remark>";

    xmlAary += "<Goods>";
    var odrAry = data.Goods;
    for (var j = 0; j < odrAry.length; j++) {
      xmlAary += "<Good>";
      xmlAary += "<GroupItemId>" + odrAry[j].Id + "</GroupItemId>";
      xmlAary += "<ProductId>" + odrAry[j].ProductId + "</ProductId>";
      xmlAary += "<GoodsId>" + odrAry[j].GoodsId + "</GoodsId>";
      xmlAary += "<Quantity>" + odrAry[j].Quantity + "</Quantity>";
      xmlAary += "<Earnest>" + odrAry[j].Earnest + "</Earnest>";
      xmlAary += "<GroupPrice>" + odrAry[j].GroupPrice + "</GroupPrice>";
      let remark = odrAry[j].BuyRemark ? odrAry[j].BuyRemark : '';
      xmlAary += "<BuyRemark>" + remark + "</BuyRemark>";
      xmlAary += "</Good>";
    }
    xmlAary += "</Goods>";
    //快递&送货时间
    if (data.DeliveryId > 0 || !isEmpty(data.DeliveryTime)) {
      xmlAary += "<Delivery>";
      xmlAary += "<DeliveryId>"+data.DeliveryId+"</DeliveryId>";
      xmlAary += "<DeliveryTime>"+data.DeliveryTime+"</DeliveryTime>";
      xmlAary += "</Delivery>";
    }
    // 当自提并且没有开启自提需要收货地址时，不传地址信息
    // 其他都需要传
    if (!data.needNotConsignee) {
      //收货信息
      xmlAary += "<Consignee>";
      xmlAary += "<Province><![CDATA[" + data.consignee.Province + "]]></Province>";
      xmlAary += "<City><![CDATA[" + data.consignee.City + "]]></City>";
      xmlAary += "<Area><![CDATA[" + data.consignee.Area + "]]></Area>";
      xmlAary += "<Address><![CDATA[" + data.consignee.Address + "]]></Address>";
      xmlAary += "<Name><![CDATA[" + data.consignee.Name + "]]></Name>";
      xmlAary += "<Mobile>" + data.consignee.Mobile + "</Mobile>";
      xmlAary += "</Consignee>";
    }
    //发票信息
    xmlAary += data.invoice;
    xmlAary += "</root>";
    // console.log(xmlAary.toString());
    return xmlAary.toString();
  },
  /**提交订单 */
  submitGroupOrder(xmlAary, callback) {
    var entity = authorize.getEntity();
    var param = {
      OrderInfo: xmlAary.toString(),
      Token: entity && entity.manager ? entity.manager.Token : '',
      FKWay: app.dns.fkWay,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
    };

    util.post("order.groupbuy.submits", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.tips(res.Message);
      }
    }, '3.0', null, false);
  },
  /**
   * 加载订单列表
   */
  loadList(index, flag, data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      Keyword: data.keywords,
      sortField: data.sortField,
      sortDirect: data.sortDirect,
      Flag: flag,
      OrderStatus: index,
      FKWay: app.dns.fkWay,
      Token: entity && entity.manager ? entity.manager.Token : ''
    };
    util.post("order.groupbuy.list", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          var content = res.Content;
          callback({
            data: content.Data,
            count: content.TotalCount
          }, entity.fkId);
        }
      }
    }, "3.0");
  },
  /**
   * 获得支付名称
   */
  get_group_status: function(o, flag) {
    if (o.Status == -1) {
      o.GroupStatus = "交易取消";
    } else if (o.status == 0) {
      o.GroupStatus = flag == 1 ? "拼团失败" : "交易失败";
    } else if (o.payStatus == 0) {
      o.GroupStatus = flag == 1 ? "待付定金" : "待付款";
      var newdate = util.addTime(o.EarnestPayHour, 1, new Date(o.AddTime));
      if (newdate < new Date()) {
        o.GroupStatus = "交易取消";
        o.Status = -1;
      }
    } else if (o.OrderId == 0) {
      o.GroupStatus = flag == 1 ? "拼团中" : "预售中";
      if (o.OrderPayStatus == 0 || o.OrderPayStatus == 3) {
        var newdate = util.addTime(o.RetainagePayHour, 1, new Date(o.EndTime));
        if (newdate < new Date()) {
          o.GroupStatus = "交易取消";
          o.Status = -1;
        }
      }
    } else {
      if (flag == 1) {
        o.GroupStatus = "拼团成功";
      } else if (o.Status == 1) {
        o.GroupStatus = "已付定金";
      } else if (o.Status == 2) {
        o.GroupStatus = "交易成功";
      }
      if (o.OrderPayStatus == 0 || o.OrderPayStatus == 3) {
        var newdate = util.addTime(o.RetainagePayHour, 1, new Date(o.EndTime));
        if (newdate < new Date()) {
          o.GroupStatus = "交易取消";
          o.Status = -1;
        }
      }
    }
  },
  /**
   * 取消订单
   * @param {Function} failCallback 失败时调用的方法
   */
  cancelOrder: function(param, callback, failCallback) {
    var entity = authorize.getEntity();
    param.Token = entity && entity.manager ? entity.manager.Token : '';
    util.post("order.groupbuy.cancel", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback();
        }
      } else {
        util.alert("取消失败");
        if (type.isFunction(failCallback)) {
          failCallback()
        }
      }

    });
  },
  /**
   * 立即支付
   */
  onPay: function(orderId, t, callback) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      token: entity && entity.manager ? entity.manager.Token : '',
      clerkToken: "0|" + this.generateTimeReqestNumber(),
      OrderId: orderId,
      Type: t
    };
    util.post("order.groupbuy.paydata", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (res.Content != "") {
          if (res.Content == "LimitBuy") {
            util.alert("商品已达到最大购买数量，系统将自动进行交易关闭！");
            callback(true);
          } else {
            orderPay.findPayOrderData(res.Content, "cashier");
          }
        }
        
      } else {
        util.alert("订单支付失败");
      }

    }, "3.0", null, false);
  },

  /**
   * 
   */
  pad2: function(n) {
    return n < 10 ? '0' + n : n
  },
  /**
   * 产生随机请求数
   */
  generateTimeReqestNumber: function() {
    var date = new Date();
    return date.getFullYear().toString() +
      this.pad2(date.getMonth() + 1) +
      this.pad2(date.getDate()) +
      this.pad2(date.getHours()) +
      this.pad2(date.getMinutes()) +
      this.pad2(date.getSeconds());
  },
  /**
   * 拼团详情
   */
  get_group_detail: (orderId, flag, callback) => {
    var entity = authorize.getEntity();
    var param = {
      OrderId: orderId,
      Flag: flag,
      FKId: entity.fkId,
      FKWay: app.dns.fkWay,
      ProprietorId: app.dns.proprietorId
    }
    util.post("order.groupbuy.getorderdetail", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        var content = res.data.Content;

        callback(content);
      }
    });
  }

}
/**
 * 退换化相关的
 */
const retreat = {
  loadList(index, data, callback) {
    var entity = authorize.getEntity();
    var param = {
      fromFKFlag: entity ? entity.fkFlag : 1,
      FromFKId: entity ? entity.fkId : 0,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      Keyword: data.keywords,
      sortField: data.sortField,
      sortDirect: data.sortDirect,
      Status: (index == -30 ? "" : index)
    };
    util.post("order.retreat.list", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        res = res.data;
        var returns = [];
        if (res.Success) {
          var content = res.Content;
          if (content.data.length > 0) {
            var items = content.data[0].ReturnItems;
            returns = content.data[0].Return;
            for (var i = 0; i < returns.length; i++) {
              for (var j = 0; j < items.length; j++) {
                if (returns[i].Id == items[j].RetreatId) {
                  if (!returns[i].items) {
                    returns[i].items = returns[i].items || [];
                  }
                  returns[i].items.push(items[j]);
                }
              }
            }
          }
        }
        callback({
          data: returns,
          count: content.count
        }, entity.fkId);
      }
    }, "3.0");
  },
  /**
   * 退换货详情
   */
  getDetail: function(oddNumber, callback) {
    var entity = authorize.getEntity();
    var param = {
      OddNumber: util.base64_encode(oddNumber.trim()),
      Token: entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };

    util.post("order.retreat.get", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          var retreat = res.Content.Retreat,
            reItem = res.Content.RetreatItem,
            retLogistics = res.Content.RetreatLogistics,
            retreatLog = res.Content.RetreatLog;
          for (var i = 0; i < retLogistics.length; i++) {
            var address = retLogistics[i].TakeAddress.replace("，", ",").split(",");
            if (address.length == 2) {
              retLogistics[i].address = address[0];
              retLogistics[i].name = address[1];
            } else if (address.length == 3) {
              retLogistics[i].address = address[0];
              retLogistics[i].name = address[1] + address[2];
            }

          }
          if (callback != undefined && typeof(callback) == "function") {
            callback(retreat, reItem, retLogistics, retreatLog);
          }
        } else {
          util.alert("操作失败：" + res.Message);
        }
      }, "3.0");
  },
  /**
   * 取消申请
   * @retreatId 退换货id
   */
  cancelApplay: function(retreatId, callback) {
    var entity = authorize.getEntity();
    var param = {
      RetreatId: retreatId,
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0,
      OperId: entity ? entity.fkId : 0,
      OperName: entity ? (entity.role.Name + "【客户】") : "",
      ProprietorId: app.dns.proprietorId
    };
    util.confirm(function() {
      util.post("order.retreat.cancel", param,
        function(res) {
          res = res.data;
          if (res.Success) {
            util.alert("取消申请成功", "温馨提示", function() {
              if (callback != undefined && typeof(callback) == "function") {
                callback();
              }
            });
          } else {
            util.alert("取消申请失败" + res.Message);
          }
        }, "3.0", null, false);
    }, null, "您确定要取消此申请吗?");
  },
  /**
   * 获得快递公司
   */
  getLogisticsList: (callback) => {
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0
    };
    util.post("Annex.logistics.list", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          if (callback != undefined && typeof(callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert("操作失败:" + res.Message);
        }
      }, "3.0");
  },
  /**
   * 退换货时发货
   */
  sendRetreat: (data, callback) => {
    var entity = authorize.getEntity();
    var param = util.mergeJsonObject(data, { 
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0,
      OperId: entity ? entity.fkId : 0,
      OperName: entity ? (entity.role.Name + "【客户】") : "",
      ProprietorId: app.dns.proprietorId
    });
    util.post("Order.retreat.send", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          util.tips("发货成功");
          if (callback != undefined && typeof(callback) == "function") {
            callback(res);
          }
        } else {
          util.tips("发货失败:" + res.Message);
        }
      }, "3.0", null, false);
  },
  /**
   * 发货拼装的xml
   * @retreatId 退换货id
   * @reItem 退换货详情
   */
  getSendRetreatXml: function(retreatId, reItem) {
    var goods = [];
    for (var i = 0; i < reItem.length; i++) {
      var item = reItem[i];
      goods.push(`<Good>
      <OrderId>${item.OrderId}</OrderId>
      <RetreatId>${retreatId}</RetreatId>
      <ItemId>${item.OrderItemId}</ItemId>
      <ProductId>${item.ProductId}</ProductId>
      <GoodsId>${item.GoodsId}</GoodsId>
      <Name><![CDATA[${item.GoodsName}]]></Name>
      <Quantity>${item.Quantity}</Quantity>
      <Price>${item.Payables}</Price>
      </Good>`);
    }
    return `<RetreatId>${retreatId}</RetreatId><DepotId>0</DepotId><IsBatch>0</IsBatch><Goods>${goods.join("")}</Goods>`
  },
  /**
   * 确认收货
   * @retreatId 退换货id
   */
  onConfirmReceive: function(retreatId, callback) {
    var entity = authorize.getEntity();
    var param = {
      RetreatId: retreatId,
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0,
      OperId: entity ? entity.fkId : 0,
      OperName: entity ? (entity.role.Name + "【客户】") : "",
      ProprietorId: app.dns.proprietorId
    };
    util.confirm(function() {
      util.post("order.retreat.finish", param,
        function(res) {
          res = res.data;
          if (res.Success) {
            if (callback != undefined && typeof(callback) == "function") {
              callback(res.Content);
            }
          } else {
            util.alert("操作失败:" + res.Message);
          }
        }, "3.0");
    }, null, "您确定已收到换货了吗");
  },
  /**
   * 获得订单详情
   */
  getOrderItem: function(oddNumber,Currency, callback) {
    var entity = authorize.getEntity();
    var param = {
      OddNumber: util.base64_encode(oddNumber),
      Token:entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };
    util.post("order.retreat.getproductinfo", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          var goodslist = res.Content;
          var orderid = goodslist[0].ParentId;
          if (goodslist[0].ParentId >= 0 && goodslist[0].IsAlone == 1) {
            orderid = goodslist[0].OrderId;
          }
          for (var i = 0, leng = goodslist.length; i < leng; i++) {
            var f = goodslist[i];
            f.IsChecked = false;
            f.return_quantity = util.calulateReduce(f.Quantity,f.Retreat);
            f.max_quantity = util.calulateReduce(f.Quantity,f.Retreat);
            f.pay_integral = (f.SalesIntegral + f.DeductionIntegral);
            f.pay_price = (f.Price - f.QuotaDiscount + f.QuotaAdjust);
            if (f.pay_price < 0) f.pay_price = 0;
            if (f.Price > 0 && (f.SalesIntegral > 0 || f.DeductionIntegral > 0)) {
              f.displayPrice = Currency + f.pay_price + "+" + f.pay_integral + "积分";
            } else if (f.Price > 0) {
              f.displayPrice = Currency + f.pay_price;
            } else if (f.SalesIntegral > 0 || f.DeductionIntegral > 0) {
              f.displayPrice = f.pay_integral + "积分";
            }
            f.translated = f.AuxRate;
            f.auxiliaryunits = [];
            f.auxiliaryunits.push({
              Name: f.AuxUnit,
              Translated: f.AuxRate
            });
            f.unitindex = 0;
            f.current_unit = f.AuxUnit;
            // if (f.AuxRate != 1) {
            //   f.translated = 1;
            //   f.auxiliaryunits.push({
            //     Name: f.Unit,
            //     Translated: 1
            //   });
            //   f.unitindex = 1;
            //   f.current_unit = f.Unit
            // }
          }
          if (callback != undefined && typeof(callback) == "function") {
            callback(goodslist, orderid);
          }
        }
      }, "3.0");
  },
  getOrderNew(oddNumber,Currency, callback){
    var entity = authorize.getEntity();
    // util.base64_encode(oddNumber)
    var param = {
      OrderId:oddNumber,
      Token:entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };
    util.post("order.retreat.pull", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          var goodslist = res.Content.OrderItems;
          var orderid = goodslist[0].ParentId;
          if (goodslist[0].ParentId >= 0 && goodslist[0].IsAlone == 1) {
            orderid = goodslist[0].OrderId;
          }
          for (var i = 0, leng = goodslist.length; i < leng; i++) {
            var f = goodslist[i];
            f.IsChecked = false;
            let retreatNum = ( f.ReableMaxQty / f.AuxRate) * f.AuxRate;
            retreatNum = retreatNum > 0 ? retreatNum : 0;
            // f.return_quantity = util.calulateReduce(f.Quantity,f.Retreat);
            console.log(retreatNum,'=-=-=');
            f.return_quantity = ( f.ReableMaxQty / f.AuxRate).toFixed(2);
            // f.max_quantity = util.calulateReduce(f.Quantity,f.Retreat);
            f.max_quantity = retreatNum;
            f.pay_integral = (f.SalesIntegral + f.DeductionIntegral);
            f.pay_price = (f.Price - f.QuotaDiscount + f.QuotaAdjust);
            if (f.pay_price < 0) f.pay_price = 0;
            if (f.Price > 0 && (f.SalesIntegral > 0 || f.DeductionIntegral > 0)) {
              f.displayPrice = Currency + f.pay_price + "+" + f.pay_integral + "积分";
            } else if (f.Price > 0) {
              f.displayPrice = Currency + f.pay_price;
            } else if (f.SalesIntegral > 0 || f.DeductionIntegral > 0) {
              f.displayPrice = f.pay_integral + "积分";
            }
            f.auxiliaryunits = [];
            f.translated = f.AuxRate;
            if(res.Content.OrderStatus == 5){
              for(var j = 0;j<f.AuxiliaryUnits.length;j++){
                var a = f.AuxiliaryUnits[j];
                if(f.AuxUnit == a.Name){
                  f.auxiliaryunits.push({
                    Name: a.Name || '',
                    Translated:a.Translated,
                    Price:a.Price,
                    Integral:a.Integral
                  });
                  f.Price = a.Price;
                }
              }
              // f.auxiliaryunits.push({
              //   Name: f.AuxUnit || '',
              //   Translated: f.AuxRate,
              //   Price:f.pay_price,
              //   Integral:f.pay_integral
              // });
              f.unitindex = 0;
            }else{
              for(var j = 0;j<f.AuxiliaryUnits.length;j++){
                var a = f.AuxiliaryUnits[j];
                if(a.Translated<=f.AuxRate){
                  f.auxiliaryunits.push({
                    Name: a.Name || '',
                    Translated:a.Translated,
                    Price:a.Price,
                    Integral:a.Integral
                  });
                  if(f.AuxUnit == a.Name){
                    f.unitindex = j;
                    f.Price = a.Price;
                  }
                }
              }
            }
            // f.current_unit = f.AuxUnit;
            // if (f.AuxRate != 1) {
            //   f.translated = 1;
            //   f.auxiliaryunits.push({
            //     Name: f.Unit,
            //     Translated: 1
            //   });
            //   f.unitindex = 1;
            //   f.current_unit = f.Unit
            // }
          }
          console.log(res);
          if (callback != undefined && typeof(callback) == "function") {
            callback(res, orderid);
          }
        }
      }, "3.1");
  },
  /**
   * 检测订单是否允许退款
   */
  checkOrder:function(orderId,callback){
    var entity = authorize.getEntity();
    var param = {
      orderId: orderId,
      token:entity && entity.manager ? entity.manager.Token : '',
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };
    util.post("payment.refund.checkorder", param,
      function (res) {
        res = res.data;
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Success);
        }
      }, "3.0");
  },
  /**
   * 提示申请
   */
  submitApply: function(xml, callback) {
    var entity = authorize.getEntity();
    var param = {
      ContextXml: xml,
      FKFlag: entity ? entity.fkFlag : 1,
      FKId: entity ? entity.fkId : 0,
      ProprietorId: app.dns.proprietorId
    };
    util.post("order.retreat.submit", param,
      function(res) {
        res = res.data;
        if (res.Success) {
          util.alert("您的申请提交成功，我们会尽快为您处理！", "成功", function() {
            router.redirect({
              path: "retreatList"
            });
          });

        } else if (res.Code == -11) {
          util.tips("该订单还未收到款项，暂不允许进行退货退款操作！");
        } else {
          util.tips(res.Message);
        }
      }, "3.0", null, false);
  },
}
export {
  fastorder,
  order,
  cart,
  fee,
  orderlist,
  orderdetail,
  retreat,
  grouporder
}

String.prototype.format = function() {
  var param = [];
  for (var i = 0, l = arguments.length; i < l; i++) {
    param.push(arguments[i]);
  }
  //var statment = param[0]; // get the first element(the original statement)
  //param.shift(); // remove the first element from array

  return this.replace(/\{(\d+)\}/g, function(m, n) {
    return param[n];
  });
}